在asp.net中如何检查Listbox中是否存在某个项目?

4
我该如何检查一个项是否已存在于Listbox中?我使用的是VS 2008 ASP.NET 3.5框架C#。我用了以下代码...
 if (ListBox1.Items.Contains(drp_branch.SelectedItem.Value + "-" + txt_acc_no.Text))
 {...}
2个回答

10

尝试这个...

string toMatch = drp_branch.SelectedItem.Value + "-" + txt_acc_no.Text;
ListItem item = ListBox1.Items.FindByText(toMatch);
if (item != null)
{
    //found
}
else
{
    //not found
}

哎呀,如果我们只知道值而不知道文本怎么办?我们得自己循环遍历 Items 或使用 Linq。 - Garr Godfrey

1

你可以使用这个来检查项目是否存在于列表框中...

string checkitem = drp_branch.SelectedItem.Value + "-" + txt_acc_no.Text;

if ((ListBox1.Items.Contains(checkitem) == true))
{
   Response.Write("Item exists");
}
else
{
   Response.Write("Item not   exists");

} 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接