简体   繁体   中英

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 on 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.

请注意,删除后可能还需要执行GridView.DataBind()。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM