How to Search Through a C# DropDownList Programmatically

后端 未结 9 1167
一生所求
一生所求 2021-02-14 05:24

I am having a hard time figuring out how to code a series of \"if\" statements that search through different dropdownlists for a specific value entered in a textbox. I was able

相关标签:
9条回答
  • 2021-02-14 06:01
    foreach (ListItem li in dropdownlist1.Items)
    {
        if (li.Value == textBox1.text)
        {
           // The value of the option matches the TextBox. Process stuff here.
        }
    }
    

    That is my suggestion for how to see if the value is in the dropdownlist.

    0 讨论(0)
  • 2021-02-14 06:01

    The solutions presented work if you want to search for an exact value in a loaded combobox.

    This solution, searches for partial values also. It uses a search button and the text portion of the dropdown box as the search criteria

    Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
    
        ' query the dropdown object
        ''''''''''''
        ' part 9457 is a "contains" sample
        ' part 111 is a "startswith" sample
    
        Dim query As IEnumerable(Of [Object]) = _
        From item In cboParts.Items _
        Where (item.ToString().ToUpper().StartsWith(cboParts.Text.ToUpper())) _
        Select (item)
    
        ' show seached item as selected item
        cboParts.SelectedItem = query.FirstOrDefault()
    
        ' "startswith" fails, so look for "contains" 
        If String.IsNullOrEmpty(cboParts.SelectedItem) Then
    
            Dim query1 As IEnumerable(Of [Object]) = _
            From item In cboParts.Items _
            Where (item.ToString().ToUpper().Contains(cboParts.Text.ToUpper())) _
            Select (item)
    
            ' show seached item as selected item
            cboParts.SelectedItem = query1.FirstOrDefault()
    
            If String.IsNullOrEmpty(cboParts.SelectedItem) Then
                MsgBox("Part is not in dropdown list")
            End If
    
        End If
    
    0 讨论(0)
  • 2021-02-14 06:04

    If you don't want to use LINQ:

            List<ComboBox> dropDowns = new List<ComboBox>();
            dropDowns.Add(comboBox1);
            dropDowns.Add(comboBox2);
    
            bool found = false;
            ComboBox foundInCombo = null;
            int foundIndex = -1;
    
            for (int i = 0; i < dropDowns.Count && found == false; i++)
            {
                for (int j = 0; j < dropDowns[i].Items.Count && found == false; j++)
                {
                    if (item == textBox1.Text)
                    {
                        found = true;
                        foundInCombo = dropDowns[i];
                        foundIndex = j;
                    }
                }
            }
    
    0 讨论(0)
提交回复
热议问题