Click here to Skip to main content
15,891,905 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi I have a winform app in c# witch permits edditing of tables from my sql database. I managed to get the tables opened and edit them but when i save the data all lines get replicated. Is there a way to do this but only edit the required fields or insert if a new one is added? I tried the update command but it wont work. the code i use is:

What I have tried:

C#
using (SqlConnection con = new SqlConnection(cs))
 {
     con.Open();
     foreach (DataGridViewRow row in dataGridView1.Rows)
     {

         if (!row.IsNewRow)
         {
             using (SqlCommand cmd = new SqlCommand("INSERT INTO temp (data1, data2, data3, data4) VALUES(@c1,@c2,@c3,@c4)", con))
             {

                 cmd.Parameters.AddWithValue("@C1", row.Cells[0].Value);
                 cmd.Parameters.AddWithValue("@C2", row.Cells[1].Value);
                 cmd.Parameters.AddWithValue("@C3", row.Cells[2].Value);
                 cmd.Parameters.AddWithValue("@C4", row.Cells[3].Value);

                 cmd.ExecuteNonQuery();

             }
         }
     }
 }
Posted
Updated 7-Dec-16 22:33pm
Comments
Tomas Takac 7-Dec-16 6:45am    
Each row should have an unique id. You need to know which row is new and which was updated. Let's say all new rows will have id=0, while edited rows will have id>0. Based on that you either issue an INSERT or UPDATE command.
Marc-IT 7-Dec-16 6:49am    
Hi Tomas,
Thanks for the reply, it makes sense.
I added a primary key as identity with autoincrement.
Do you have a code sample of how i can check for the id ?

1 solution

Solution Step 1:Ready all you data ans create a DataTable to save the data.
Step 2: Pass Datatable to Sql to save data.

c# - How to insert a data table into SQL Server database table? - Stack Overflow[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900