如何删除DataTable中的行

时间:2014-03-16 17:01:35

标签: c# mysql database

 foreach(DataRow row in dt.Rows)
 {
  if (row["ProductID"].ToString().Equals(txtBarcode.Text.Trim()))
  {
    row.Delete();
    txtBarcode.Clear();

  }
 }
 adapt.SelectCommand.Parameters.AddWithValue("@idText", txtBarcode.Text);
 adapt.Fill(dt);
 dgItems.ReadOnly = true;
 dgItems.DataSource = dt;
 txtBarcode.Clear();

当用户尝试在gridview中存在时插入相同的条形码时,我使用此代码删除行,但是有错误。首先,当我输入重复的条形码时,它会删除该行,但当我输入另一个重复的条形码时,它会显示An unhandled exception of type System.Data.DeletedRowInaccessibleException' occurred in System.Data.dll

Additional information: Deleted row information cannot be accessed through the row.

1 个答案:

答案 0 :(得分:3)

    foreach(DataRow row in dt.Rows)
     {
      if (row["ProductID"].ToString().Equals(txtBarcode.Text.Trim()))
      {
        row.Delete();
        txtBarcode.Clear();

      }
     }
   dt.AcceptChanges();