Click here to Skip to main content
15,921,226 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
there is a DatagridView.the scenario is when I change the value of some rows and click on SaveButton, the table in database will be updated.For doing this,I made a list of objects and put all rows of DGV into this list(every row of DGV is mapped to One object). then in a foreach loop I read this list and update the related row of table in database.I know this way has less performance because it connect to db multiple times.Is there any way to Update or insert multiple rows easily?

C#
List<Person> lst = PutRowsOfDGVIntoList();
if (lst != null && lst.Count != 0)
{

    foreach (var person in lst)
    {
      if (!pda.ifExistPerson())//if current row don't exist in Db insert new person else update
      {
         if (!pda.InsertPerson(person))//insert
          throw new Exception();

      }
      else
      {
         if (!pda.UpdatePerson(person))//update
                    throw new Exception();
      }
   }
}
Posted
Updated 22-Feb-14 2:07am
v4

If you use a DataAdapter and bind your data, then it is all handled for you: http://msdn.microsoft.com/en-us/library/fbk67b6z(v=vs.90).aspx[^]

The link includes sample code to do it all!
 
Share this answer
 
Comments
CHill60 22-Feb-14 8:14am    
Overlap (again!) - 5'd
There are several alternatives to your approach - not least only connect to the database once at the beginning of your write process and disconnect when finished (not once per object)

Here is a list of things to try[^]
 
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