DataTable + entering row at specific row in C#
I have a Data table and I want to enter a row at the beginning and end of the table how can I achieve this:
C# code:
Guid tempGuid1 = new Guid();
dt1.Rows[0]["ID"] = tempGuid1;
dt1.Rows[0]["Name"] = "Select a WishList";
Guid tempGuid = new Guid();
dt1.Rows.Add(tempGuid, "Create a new WishList");
Ok after I fill the table I want to enter a brand new row at top of the table
Guid tempGuid1 = new Guid();
dt1.Row开发者_如何学运维s[0]["ID"] = tempGuid1;
dt1.Rows[0]["Name"] = "Select a WishList";
and than at the end of the table
Guid tempGuid = new Guid();
dt1.Rows.Add(tempGuid, "Create a new WishList");
I can enter at the end but the brand new row giving me problems, currently the code overwrites the top row which is row[0]
.
You can use the InsertAt
method to insert a new row at the position you want.
Referencing row[0]
means you are overwriting the data already there, as you have discovered.
DataRow newRow = dt1.NewRow();
newRow["ID"] = tempGuid1;
newRow["Name"] = "Select a WishList";
dt1.Rows.InsertAt(newRow, 0);
Consider the DataRowCollections "InsertAt" method. It accepts a data row and an integer representing the row index at which the row should be inserted. So you can use this code:
Guid tempGuid = new Guid();
DataRow firstRow = dt1.NewRow();
firstRow["ID"] = tempGuid;
firstRow["Name" = "Select a Wishlist";
dt1.InsertAt(firstRow, 0);
精彩评论