检查列表框是否包含某个元素

时间:2015-07-02 07:14:47

标签: c# winforms listbox

我知道这个问题已经多次发布在这里,但是我已经阅读了这些帖子,对我来说没什么用,所以我决定在这里问一下。

我只想检查列表框中是否已存在某个字符串。我试过了

   listBox.Items.Contains("stringToMatch")

但我一无所获。

我也试过

 foreach (var item in form1.filterTypeList.Items)
                {
                    if (item.ToString() == "stringToMatch")
                    {
                        break;              
                    } 

他什么也没发现。为什么?我该如何解决?

3 个答案:

答案 0 :(得分:0)

尝试使用这种方式... FindByText

strig toMatch = "stringToMatch";
ListItem item = ListBox1.Items.FindByText(toMatch);
if (item != null)
{
    //found
}
else
{
    //not found
}

答案 1 :(得分:0)

请尝试如下。我正在列表视图项上循环,以根据项标记或项文本搜索字符串。

  for (int i = 0; i <= ListView.Items.Count - 1; i++) 
            {
                itmX = ListView.Items.Item(i); 

                if (itmX.Text.ToString() = "stringToMatch")
                {
                  break;              
                } 
            }

OR

for (int i = 0; i <= ListView.Items.Count - 1; i++) 
    {
        itmX = ListView.Items.Item(i); 

        if (itmX.Tag.ToString() = "stringToMatch")
        {
          break;              
        } 
    }

答案 2 :(得分:0)

现在这么简单,你只需先找到列表框项集合中该项的索引,然后使用listbox listBox1.FindStringExact的这个函数。

private void FindMySpecificString(string searchString) 
{ 
   // Ensure we have a proper string to search for. 
   if (searchString != string.Empty) 
   { 
      // Find the item in the list and store the index to the item. 
      int index = listBox1.FindStringExact(searchString); 
      // Determine if a valid index is returned. Select the item if it is valid. 
      if (index != ListBox.NoMatches) 
         listBox1.SetSelected(index,true); 
      else 
         MessageBox.Show("The search string did not find any items in the ListBox that exactly match the specified search string"); 
   } 
}

访问以下网站以获得更多说明和示例 https://msdn.microsoft.com/en-us/en-en/library/81wes5yz(v=vs.110).aspx

相关问题