DataTable Rows.IndexOf()
-
18-09-2019 - |
Question
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);
}
}
Solution
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;
}
}
OTHER TIPS
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.