views:

1207

answers:

2

I am trying to find a row and then delete that row from a datatable. I keep getting nIndex = -1. Anyone have suggestions?

protected void cbxSelected_CheckedChanged(object sender, EventArgs e)
{
 CheckBox checkbox = (CheckBox)sender;
 GridViewRow row = (GridViewRow)checkbox.NamingContainer;
 string sSampleId = row.Cells[1].Text;

 if (!string.IsNullOrEmpty(sSampleId))
 {
  DataTable dt;

  if (ViewState["dtTemp"] != null)
  {
   dt = (DataTable)ViewState["dtTemp"];
  }
  else
  {
   dt = new DataTable();
   dt.Columns.Add("sample_id");
  }

  DataRow dr;
  string[] drow = new string[] { sSampleId };
  dr = dt.NewRow();
  dr.ItemArray = drow;

  if (checkbox.Checked == true)
  {
   dt.Rows.Add(dr);
  }
  else if (checkbox.Checked == false)
  {
   int nIndex = dt.Rows.IndexOf(dr);
   dt.Rows.RemoveAt(nIndex);
  }

  ViewState.Add("dtTemp", dt);
 }
}
A: 

Since you create a new DataRow

dr = dt.NewRow();

you won't find it in the DataTable.

You want to remove the row that IS in the DataTable:

int nIndex = dt.Rows.IndexOf(row);

not

int nIndex = dt.Rows.IndexOf(dr);

Edit: Or maybe not. You'll probably have to loop through the entire DataTable and compare the value in the column:

for (var i = dt.Rows.Count; i >= 0; i--)
  if (dt.Rows[i].Cells[1].Text == sSampleId) {
    dt.Rows.Remove(i);
    break;
  }
}
Sani Huttunen
I thought by building up the datarow that I would be able to find that row in the datatable. I remember doing this in vb, but c# appears to be a little more stingy. I tried your suggestion of looping through the table and deleting the row on a find, this works. Thanks for the input.
Kris
A: 

To find and delete a row in an ADO.NET DataTable given its ID:

DataRow[] found = dt.Select("sample_id = " + sample_id);
if (found.Length < 0)
{
   found[0].Delete();
}

Note that there's a difference between Delete and Remove. Delete changes the row's state to RowState.Deleted, which makes it disappear from the DataTable for most purposes. But it still exists. This is important if you're using a data adapter to sync the DataTable up with an underlying database table: the adapter will delete the underlying row when you call its Update method and only then remove the row from the Rows collection.

If you're not using a data adapter, it's OK to use Remove to remove a row.

Robert Rossney