如何从asp.net中删除数据表中的行 [英] how to delete row from datatable in asp.net
问题描述
我有一个gridview,我用datatable绑定它。我想为gridview_rowdeleting事件编写代码,当我点击gridview行的删除链接时,该行应从datatable中删除,当单击另一行delete时,则当前行和上一行都应从datatable中删除。我尝试了很多,但我无法解决问题。请帮帮我。
提前感谢。
以下是我的代码:
i have a gridview, and i bind that with datatable. i want to write code for gridview_rowdeleting event, when i click on delete link of gridview row, this row should remove from datatable, and when click another row delete, then both current and previous row should delete from datatable. i try a lot but i cannot fix the problem. please help me.
thanks in advance.
below is my code:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int intforumid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
int ii = e.RowIndex;
lst.Add(ii);
// ViewState["ind"] = ViewState["ind"] + e.RowIndex.ToString() + ",";
ViewState["ind"] = ViewState["ind"] + e.RowIndex.ToString() + ",";
List<int> del = new List<int>();
string[] str = ViewState["ind"].ToString().Split(',');
for (int k = 0; k < str.Length; k++)
{
if (str[k] != "")
{
//foreach (DataRow d in dt.Rows)
//{
// if (Convert.ToString(d["id"]) == str[k])
// {
del.Add(Convert.ToInt32(str[k]));
// dt.Rows.RemoveAt(Convert.ToInt32(str[k]));
// dt.AcceptChanges();
// }
//}
}
}
int i1 = 0;
for (int s = 0; s < del.Count; s++)
{
i1 = s;
dt.Rows.RemoveAt(i1++);
dt.AcceptChanges();
}
GridView1.DataSource = null;
GridView1.DataSource = dt;
GridView1.DataBind();
}
推荐答案
你写了太多的东西来做一个简单的删除,不知道为什么。
您是否可以尝试通过注释RowDeleting事件一段时间来检查代码并检查它是否适合您?
You have written too much of stuffs to do a simple delete, not sure why.
Can you try following code by just commenting out your RowDeleting event for sometime and check if it works for you?
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int index = Convert.ToInt32(e.RowIndex);
DataTable dt = ViewState["dt"] as DataTable; //datatable stored previousely in viewstate
dt.Rows[index].Delete();
dt.AcceptChanges();
ViewState["dt"] = dt; //save the new values back to the viewstate
GridView1.DataSource = dt;
GridView1.DataBind();
}
注意:这将删除数据表中不是来自数据库的行,您需要为此编写逻辑进一步。
希望,它有帮助:)
Note: This will delete the row from the datatable not from the database, for which you need to write the logic further.
Hope, it helps :)
这篇关于如何从asp.net中删除数据表中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!