所以现在,我尝试了以下代码,但它只删除了一个列表项。它似乎删除了第一个项目后,列表刷新,另一个选中的项目不会被删除。如何解决这个问题,以便从数据库表中删除所有选中的项目?
//NewFoodInputTextBox is an ASP.NET TextBox which takes input
//just fine and outputs status/error updates as well.
protected void DeleteFoodButton_Click(object sender, EventArgs e)
{
try
{
int delCount = 0;
int prevDelCount = 0;
string status = "";
foreach (ListItem Item in FoodChecklist.Items)
{
if (Item.Selected)
{
FoodList.Delete(); //only deletes 1 item
prevDelCount = delCount;
delCount += 1;
if (delCount > prevDelCount) //printing out the deleted items
{
status = status + " " + Item.ToString(); //returns all checked items normally
}
}
}
if (delCount == 0)
{
NewFoodInputTextBox.Text = "Nothing selected to delete";
}
else
{
NewFoodInputTextBox.Text = "Deleted the following: " + status;
}
}
catch
{
NewFoodInputTextBox.Text = "Unexpected behavior detected";
}
}
答案 0 :(得分:0)
您的问题是您使用的是Selected
项,而不是Checked
项。这些是两个不同的东西(选中是蓝色突出显示,选中是复选框)。在您的条件中使用Checked
属性,一切都应该正常。
附注,您还可以使用CheckedItems
中ListView
的{{1}}属性来简化代码。
foreach