数据表行.IndexOf()
我试图找到一行,然后从数据表中删除该行。我不断得到 nIndex = -1。有人有建议吗?
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);
}
}
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于您创建了一个新的 DataRow,因此
您不会在 DataTable 中找到它。
您想要删除数据表中的行:
而不是
编辑:
或者也许不是。您可能必须循环遍历整个 DataTable 并比较列中的值:
Since you create a new DataRow
you won't find it in the DataTable.
You want to remove the row that IS in the DataTable:
not
Edit:
Or maybe not. You'll probably have to loop through the entire DataTable and compare the value in the column:
要查找并删除 ADO.NET
DataTable
中给定 ID 的行:请注意,
Delete
和Remove
之间存在差异。Delete
将行的状态更改为RowState.Deleted
,这使其在大多数情况下从DataTable
中消失。但它仍然存在。如果您使用数据适配器将DataTable
与基础数据库表同步,这一点很重要:当您调用其Update
方法时,适配器将删除基础行,并且然后才从Rows
集合中删除该行。如果您不使用数据适配器,则可以使用
Remove
来删除行。To find and delete a row in an ADO.NET
DataTable
given its ID:Note that there's a difference between
Delete
andRemove
.Delete
changes the row's state toRowState.Deleted
, which makes it disappear from theDataTable
for most purposes. But it still exists. This is important if you're using a data adapter to sync theDataTable
up with an underlying database table: the adapter will delete the underlying row when you call itsUpdate
method and only then remove the row from theRows
collection.If you're not using a data adapter, it's OK to use
Remove
to remove a row.