question

KwebenaAcquah-9104 avatar image
0 Votes"
KwebenaAcquah-9104 asked ·

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

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)



dotnet-csharpwindows-wpf
capture.png (21.7 KiB)
capturee.png (4.5 KiB)
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Viorel-1 avatar image
0 Votes"
Viorel-1 answered ·

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.

· 5 ·
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

i actually had not error but just one thing; THE @IDNO seems to reupdating IDNO even when it has different IDNO

can you help make it to be able to update each row with different IDNO please is it possible ? if yes please help me Sir (thanks in advance)

0 Votes 0 ·
Viorel-1 avatar image Viorel-1 KwebenaAcquah-9104 ·

Do you have another code that reads the sequence of numbers (one row) from database to textbox? How did you initialise the textbox? Was it empty, then entered manually?

0 Votes 0 ·

yes i do i just updated the question please peruse through to see for your self Sir

i have an idea, what if i have a different textbox that would hold the IDNO columns number of each selected row and we update each row according to the IDNO numbers in the textbox simultaneously row after row

0 Votes 0 ·
Show more comments

please sir it did not work as expected it was actually updating just one row, i actually want to be able to update each rows as selected from the data grid for each IDNO please sir help me your own way.

0 Votes 0 ·
karenpayneoregon avatar image
0 Votes"
karenpayneoregon answered ·

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



f1.png (12.8 KiB)
f2.png (5.2 KiB)
·
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.