开发者

Problem when trying to delete row from DataTable

I've got a DataTable floating in a session variable, that is tied to a GridView.

I've programmed a Delete button into the GridView, which calls a method to delete that row as follows

private void DeleteRecordByID(int ID)
{
    DataTable dt = (DataTable)Session["tempPermissions"];
    DataRow rowDelete = dt.Rows[ID];
    dt.Rows.Remove(rowDelete);
}

I've got two test records sitting in my DataTable that get loaded from a database.

My issue is that when I click delete o开发者_如何学运维n a record, I get the following error

System.IndexOutOfRangeException: There is no row at position 22.

Even though there is a record in the DataTable that has ID of 22..

Anybody know why this is happening?


The indexer is expecting the index of the row, not the ID.

Your rows may be

1
15
29
31

But the indexes are merely 0 through 3.

There are several methods of finding a row within a DataTable, ranging from built-in methods on DataTable to using LINQ. A DataTable-centered method is to define a primary key column on the table, such as

DataColumn idColumn = dt.Columns["ID"];
dt.PrimaryKey = new[] { idColumn };

This allows you to use the DataTable.Rows.Find(object key) method to retrieve your row.

DataRow row = dt.Rows.Find(22);

If no row exists with the given key, the result will be null. As such, validate against null before doing any operations with the output.


Note that you may also need to do a GridView.DataBind() after the delete.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜