Friday, May 30, 2008

DataTable.Rows.InsertAt(DataRow, Position)

I wanted to interchange row positions of some records in my data table. Actually I wanted to search some records and bring those records on top of the data table. So I wrote this piece of code.

DataRow[] foundRows = dt.Select("firstName+' '+lastName='" + SearchString + "'");

for (int i = 0; i <>

{
dt.Rows.Remove(foundRows[i]);
dt.Rows.InsertAt(foundRows[i],i);
}

I didn't see any wrong with this code so I debugged to test the code. what I was expected to get the selected records on top of the data table as first few rows but the output was not what I was expected. replaces first few columns showed as blank records. When inserting records through InsertAt method it has inserted blank columns. so I checked the data row (foundRows[i]) just before inserting to the data table through InsertAt method and it showed the values of the record properly.

Finally my conclusion was after Inserted the new record to the data table through InsertAt method, those records become blank records. So I changed the above code as,

DataRow[] foundRows = dt.Select("firstName+' '+lastName='" + SearchString + "'");

for (int i = 0; i < foundRows.Length; i++)
{
DataRow dr = dt.NewRow();
dr["id"] = foundRows[i]["id"];
dr["FirstName"] = foundRows[i]["FirstName"];
dr["LastName"] = foundRows[i]["LastName"];
dr["Title"] = foundRows[i]["Title"];
dr["Location"] = foundRows[i]["Location"];
dt.Rows.Remove(foundRows[i]);
dt.Rows.InsertAt(dr,i);
}


And it worked perfectly. I had to create a new data row, assign the selected data row to that and insert newly created data row to the data table.

1 comment:

  1. Just so you know, you just saved my life.

    Thanks!

    ReplyDelete