how to upate series of values from one textbox back to there respective columns in the database ?

KwebenaAcquah-9104 306 Reputation points
2021-03-07T00:51:23.103+00:00

i am having a datagrid like this;

75082-capture.png

when each row is selected each columns shows up in the a textbox like this;

 DataGrid dg = sender as DataGrid;  
            DataRowView dr = dg.SelectedItem as DataRowView;  
            if (dr != null)  
            {  
                if (dgvGrade.SelectedItems.Count > 0)  
                {  
                    foreach (var obj in dgvGrade.SelectedItems)  
                    {  
                        str += dr["ENGLISH"] + "   " + dr["MATH"] + "    " + dr["SOCIAL"] + "   " + dr["SCIENCE"] + "   " + dr["PRETECH"] + "   " + dr["ICT"] + "   " + dr["RME"] + "  " + dr["HOMEECOMICS"] + "  " + dr["HISTORY"] + "   " + dr["OWOP"] + "   " + dr["CREATIVEART"] + "   " + dr["FRENCH"] + "   " + dr["LANGUAGE"] + "\n";  
                    }  
                }  
                else  
                {  
                    //DO NOTHING  
                }  
                txtresults.Text = str;  
            }  

74964-capturee.png

ok to be more lucid; each value from the textbox is coming from each column in the datagrid say; Column MATH = 8, Column ENGLIS = 9, Column science = 10; etc. so when each rows is selected each columns shows in textbox1 so my question is; how can i save this figures back to there respective columns in the database; AFTER changes must have been made to this values. that is say; Column MATH value back to Column MATH and likewise english and science.
i would like to update each value from the textbox back into its respect columns in the database; below is what i have tried so far:

SqlConnection Conn = new SqlConnection(shoolmanangmentconn);  
             SqlCommand cmd = new SqlCommand("UPDATE tbl_TestingTheApplicationSubject SET (MATH=@MATH, ENGLISH=@ENGLISH, SOCIAL=@SOCIAL, SCIENCE=@SCIENCE, RME=@RME, PRETECH=@PRETECH, HOMEECOMICS=@HOMEECOMICS,  HISTORY=@HISTORY, ICT=@ICT, FRENCH=@FRENCH, CREATIVEART=@CREATIVEART, LANGUAGE=@LANGUAGE WHERE IDNO=@IDNO)", Conn);  
              cmd.CommandType = CommandType.Text;  
              if (txtresults.Text.Contains(','))  
                {  
                 string[] arryval = txtresults.Text.Split(',');//split values with ‘,’    
                 int j = arryval.Length;  
                 int i = 0;  
                 for (i = 0; i < j; i++)  
                 {  
                    cmd.Parameters.Clear();  
                    cmd.Parameters.AddWithValue("@ENGLISH", arryval[i]);  
                    cmd.Parameters.AddWithValue("@MATH", arryval[i]);  
                    cmd.Parameters.AddWithValue("@SOCIAL", arryval[i]);  
                    cmd.Parameters.AddWithValue("@SCIENCE", arryval[i]);  
                    cmd.Parameters.AddWithValue("@RME", arryval[i]);  
                    cmd.Parameters.AddWithValue("@PRETECH", arryval[i]);  
                    cmd.Parameters.AddWithValue("@HOMEECOMICS", arryval[i]);  
                    cmd.Parameters.AddWithValue("@HISTORY", arryval[i]);  
                    cmd.Parameters.AddWithValue("@ICT", arryval[i]);  
                    cmd.Parameters.AddWithValue("@FRENCH", arryval[i]);  
                    cmd.Parameters.AddWithValue("@CREATIVEART", arryval[i]);  
                    cmd.Parameters.AddWithValue("@LANGUAGE", arryval[i]);  
                    Conn.Open();  
                    cmd.ExecuteNonQuery();  
                 }  
              }  

please can some teach to do the right thing please i need help; (i am using c# wpf)

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,668 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,215 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 112K Reputation points
    2021-03-07T06:26:35.48+00:00

    In order to update one row, you must identify it, by IDNO column. The query contains @IDNO, but you did not add it to Parameters. Clarify the value of IDNO. (Currently it is 1). Probably you have it from other code that reads the row and keeps it in some member variable.

    Also add OWOP and remove “( )”.

    Try adjusting the next modified code:

    SqlConnection Conn = new SqlConnection(shoolmanangmentconn);
    Conn.Open();
    SqlCommand cmd = new SqlCommand("UPDATE tbl_TestingTheApplicationSubject SET MATH=@MATH, ENGLISH=@ENGLISH, SOCIAL=@SOCIAL, SCIENCE=@SCIENCE, RME=@RME, PRETECH=@PRETECH, HOMEECOMICS=@HOMEECOMICS,  HISTORY=@HISTORY, OWOP=@OWOP, ICT=@ICT, FRENCH=@FRENCH, CREATIVEART=@CREATIVEART, LANGUAGE=@LANGUAGE WHERE IDNO=@IDNO", Conn);
    cmd.CommandType = CommandType.Text;
    string[] arryval = txtresults.Text.Split( new[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries );
    int i = 0;
    cmd.Parameters.Clear();
    cmd.Parameters.AddWithValue("@IDNO", 1); // TODO: use correct value of IDNO
    cmd.Parameters.AddWithValue("@ENGLISH", arryval[i++]);
    cmd.Parameters.AddWithValue("@MATH", arryval[i++]);
    cmd.Parameters.AddWithValue("@SOCIAL", arryval[i++]);
    cmd.Parameters.AddWithValue("@SCIENCE", arryval[i++]);
    cmd.Parameters.AddWithValue("@PRETECH", arryval[i++]);
    cmd.Parameters.AddWithValue("@ICT", arryval[i++]);
    cmd.Parameters.AddWithValue("@RME", arryval[i++]);
    cmd.Parameters.AddWithValue("@HOMEECOMICS", arryval[i++]);
    cmd.Parameters.AddWithValue("@HISTORY", arryval[i++]);
    cmd.Parameters.AddWithValue("@OWOP", arryval[i++]);
    cmd.Parameters.AddWithValue("@CREATIVEART", arryval[i++]);
    cmd.Parameters.AddWithValue("@FRENCH", arryval[i++]);
    cmd.Parameters.AddWithValue("@LANGUAGE", arryval[i++]);
    cmd.ExecuteNonQuery();
    

    Show the errors if it does not work.


1 additional answer

Sort by: Most helpful
  1. Karen Payne MVP 35,031 Reputation points
    2021-03-07T01:26:59.003+00:00

    Hello,

    For this code sample, let's say each value in the TextBox are int's and we know one line has values.

    Note: This is done in Windows Form and WPF

    Add these two classes to your project.

    StringExtensions class

    Ensures we can split the line if here is more than one space between each value and from a string return a string array.

    public static class StringExtensions  
    {  
        public static string[] RemoveDoubleSpacesToArray(this string sender)  
        {  
            var options = RegexOptions.None;  
            var regex = new Regex("[ ]{2,}", options);  
            return regex.Replace(sender, " ").Split(' ');  
        }  
    }  
    

    NumericArrayExtensions class

    • AllInt returns true if all elements in an array are int, otherwise false.
    • ToIntegerArray converts a string array to an int array

    Code

        public static class NumericArrayExtensions  
        {  
            public static bool AllInt(this string[] sender) =>   
                sender.SelectMany(item => item.ToCharArray()).All(char.IsNumber);  
              
            public static int[] ToIntegerArray(this string[] sender)  
            {  
                var intArray = Array  
                    .ConvertAll(sender,  
                        (input) => new  
                        {  
                            IsInteger = int.TryParse(input, out var integerValue),  
                            Value = integerValue  
                        })  
                    .Where(result => result.IsInteger)  
                    .Select(result => result.Value)  
                    .ToArray();  
          
                return intArray;  
            }  
        }  
    

    Form code

    Only shows how to get the int values to the Output window. In your case add them to your Parameters for sending to the database.

    public partial class Form1 : Form  
    {  
        public Form1()  
        {  
            InitializeComponent();  
        }  
      
        private void button1_Click(object sender, EventArgs e)  
        {  
            var line = textBox1.Lines.FirstOrDefault(data => !string.IsNullOrWhiteSpace(data));  
              
            if (!string.IsNullOrWhiteSpace(line))  
            {  
                var cleanUpData = line.RemoveDoubleSpacesToArray();  
      
                if (cleanUpData.AllInt())  
                {  
                    var integers = cleanUpData.ToIntegerArray();  
      
                    for (int index = 0; index < integers.Length; index++)  
                    {  
                        Debug.WriteLine($"{index}\t{integers[index]}");  
                    }  
                }  
            }  
              
        }  
    }  
    

    75088-f1.png

    WPF

    <Window  
        x:Class="WpfApp1.MainWindow"  
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
        xmlns:local="clr-namespace:WpfApp1"  
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
        Title="MainWindow"  
        Width="455"  
        Height="186"  
        mc:Ignorable="d">  
        <Grid>  
            <TextBox  
                x:Name="textBox1"  
                Width="343"  
                Height="73"  
                Margin="25,19,0,0"  
                HorizontalAlignment="Left"  
                VerticalAlignment="Top"  
                AcceptsReturn="True"  
                Text="TextBox"  
                TextWrapping="Wrap" />  
            <Button  
                x:Name="button1"  
                Width="69"  
                Height="29"  
                Margin="25,109,0,0"  
                HorizontalAlignment="Left"  
                VerticalAlignment="Top"  
                Click="button1_Click"  
                Content="Button" />  
      
        </Grid>  
    </Window>  
    

    Code behind

    public partial class MainWindow : Window  
    {  
        public MainWindow()  
        {  
            InitializeComponent();  
      
            textBox1.Text = @"  
      
    8   9     11     12    13   14    15   33   37   38   39  24  
      
    ";  
        }  
      
        private void button1_Click(object sender, RoutedEventArgs e)  
        {  
            var line = textBox1.Text.Trim();  
            if (!string.IsNullOrWhiteSpace(line))  
            {  
                var cleanUpData = line.RemoveDoubleSpacesToArray();  
      
                if (cleanUpData.AllInt())  
                {  
                    var integers = cleanUpData.ToIntegerArray();  
      
                    for (int index = 0; index < integers.Length; index++)  
                    {  
                        Debug.WriteLine($"{index}\t{integers[index]}");  
                    }  
                }  
            }  
        }  
    }  
    

    74967-f2.png

    0 comments No comments