protected void btndelete_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
for (int i = 0; i < listview1.Items.Count; i++)
{
ListViewDataItem items = listview1.Items[i];
CheckBox chkBox = (CheckBox)items.FindControl("chkdel");
if (chkBox.Checked == true)
{
if (Session["CurrentTable"] != null)
{
dt = (DataTable)Session["CurrentTable"];
dt.Rows.RemoveAt(i);
}
}
else
{
}
}
Session["CurrentTable"] = dt;
listview1.DataSource = dt;
listview1.DataBind();
BindDataToGridviewDropdownlist();
}
这里只删除一行。如何删除listview中的多个已检查项?
答案 0 :(得分:0)
正如Hans Derks在评论中所提到的那样,您每次都会从会话中获取数据表,但实际上并未使用Session["CurrentTable"]=dt;
进行更新,例如:
protected void btndelete_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
for (int i = 0; i < listview1.Items.Count; i++)
{
ListViewDataItem items = listview1.Items[i];
CheckBox chkBox = (CheckBox)items.FindControl("chkdel");
if (chkBox.Checked == true)
{
if (Session["CurrentTable"] != null)
{
dt = (DataTable)Session["CurrentTable"];
dt.Rows.RemoveAt(i);
Session["CurrentTable"]=dt;
listview1.DataSource = dt;
listview1.DataBind();
}
}
else
{
}
}
BindDataToGridviewDropdownlist();
}
答案 1 :(得分:0)
Pranav答案的重构版本:
protected void btndelete_Click(object sender, EventArgs e)
{
// Get the Table from the session.
DataTable dt = (DataTable)Session["CurrentTable"];
// Only actually proceed, if we have a value.
if(dt != null)
{
// Loop through each item.
for (int i = 0; i < listview1.Items.Count - 1; i++)
{
// Find the checkbox to determine if it's checked.
ListViewDataItem items = listview1.Items[i];
CheckBox chkBox = (CheckBox)items.FindControl("chkdel");
if (chkBox.Checked == true)
{
// Remove the row at the current index.
dt.rows.RemoveAt(i);
}
}
// Update the session and rebind the data.
Session["CurrentTable"] = dt;
listview1.DataSource = dt;
listview1.DataBind();
BindDataToGridviewDropdownlist();
}
}
答案 2 :(得分:0)
这对我有用.....
protected void btndelete_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
if (Session["CurrentTable"] != null)
{
dt = (DataTable)Session["CurrentTable"];
int j = 0;
for (int i = 0; i < listview1.Items.Count; i++)
{
ListViewDataItem items = listview1.Items[i];
CheckBox chkBox = (CheckBox)items.FindControl("chkdel");
if (chkBox.Checked == true)
{
dt.Rows.RemoveAt(j);
dt.AcceptChanges();
}
else
{
j++;
}
}
Session["CurrentTable"] = dt;
listview1.DataSource = dt;
listview1.DataBind();
BindDataToGridviewDropdownlist();
}
}