您可以通过以下方法来比较并从ASP.NET WebForm中的ListBox中删除项目:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// 添加项目到ListBox
listBoxItems.Items.Add(new ListItem("Item 1", "1"));
listBoxItems.Items.Add(new ListItem("Item 2", "2"));
listBoxItems.Items.Add(new ListItem("Item 3", "3"));
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
// 遍历ListBox中的项目
for (int i = listBoxItems.Items.Count - 1; i >= 0; i--)
{
// 比较并删除指定的项目
if (listBoxItems.Items[i].Text == "Item 2")
{
listBoxItems.Items.RemoveAt(i);
}
}
}
在上面的示例中,我们使用循环遍历ListBox中的项目,并使用if语句来比较每个项目的文本值。如果项目的文本值与指定的值相等,则使用RemoveAt方法从ListBox中删除该项目。
请注意,我们从ListBox的末尾开始遍历并删除项目,以避免由于删除了一个项目而导致索引位置发生变化。