尝试从数据表中删除行时出现问题
我有一个浮动在会话变量中的 DataTable,它与 GridView 绑定。
我已在 GridView 中编写了一个“删除”按钮,该按钮调用一个方法来删除该行,如下所示。
private void DeleteRecordByID(int ID)
{
DataTable dt = (DataTable)Session["tempPermissions"];
DataRow rowDelete = dt.Rows[ID];
dt.Rows.Remove(rowDelete);
}
我的 DataTable 中有两条从数据库加载的测试记录。
我也会收到以下错误
System.IndexOutOfRangeException: There is no row at position 22.
我的问题是,当我单击一条记录上的“删除”时,即使数据表中有一条 ID 为 22 的记录,
。有人知道为什么会发生这种情况吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
索引器需要行的索引,而不是ID。
您的行可能是
但索引仅为 0 到 3。
在 DataTable 中查找行的方法有多种,从 DataTable 上的内置方法到使用 LINQ。以 DataTable 为中心的方法是在表上定义一个主键列,例如。
这允许您使用
DataTable.Rows.Find(object key)
方法来检索您的行。如果不存在具有给定键的行,则结果将为
null
。因此,在对输出执行任何操作之前,请针对 null 进行验证。The indexer is expecting the index of the row, not the ID.
Your rows may be
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
This allows you to use the
DataTable.Rows.Find(object key)
method to retrieve your row.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() 操作。
Note that you may also need to do a GridView.DataBind() after the delete.