C # комбинированный список с полем поиска - PullRequest
0 голосов
/ 29 августа 2018

Я хочу ввести значения в свой выпадающий список и отфильтровать комбо-элементы там, где ни один элемент не содержит набираемого мной текста.

Так что, если у меня есть выпадающий список со значениями {"one", "two", "three"}

Я мог бы выбрать поле со списком и набрать "o", что бы дать мне "один" и "два" в качестве оставшихся вариантов.

Я вижу, что этот вопрос задавался пару раз, но все ответы очень длинные и неловкие - мой любимый пример пока что this.

Кто-нибудь знает какой-то более разумный способ сделать это?

Ответы [ 2 ]

0 голосов
/ 30 августа 2018

Для тех, кто хочет это сделать, вот код, который я использовал (vb.net)

Private Sub ComboKeyPressed() 'cbRPP = the checkbox. I true cbRPP.Sorted = true so I don't have to manually resort items
    SyncLock "ComboKeyPressed"
        cbRPP.DroppedDown = True
        Cursor.Current = Cursors.Default

        Dim s As String = cbRPP.Text.ToLower()
        Dim toShow As IEnumerable(Of String) = cbRPPItems.Where(Function(x) x.ToLower().Contains(s.ToLower()))

        If Not toShow.Any() Then
            cbRPP.Items.Clear()
        End If

        Dim cbItems = New List(Of String)(cbRPP.Items.OfType(Of String).ToList())

        Dim toRemove = cbItems.Except(toShow).ToList()
        Dim toAdd = toShow.Except(cbItems)

        For Each item In toAdd
            cbRPP.Items.Add(item)
        Next

        For Each item In toRemove
            cbRPP.Items.Remove(item)
        Next
    End SyncLock
End Sub
0 голосов
/ 29 августа 2018

Вы можете использовать этот код:

    //Elements of the combobox
    string[] ComboxBoxItems = { "one", "two", "three" };

    private void comboBox1_TextUpdate(object sender, EventArgs e)
    {
        //Gets the items that contains the search string and orders them by its position. Without the union items that don't contain the
        //search string would be permanently removed from the combobox.
        string[] UpdatedComboBoxItems = ComboxBoxItems.Where(x => x.Contains(comboBox1.Text)).OrderBy(x => x.IndexOf(comboBox1.Text)).ToArray();

        //Removes every element from the combobox control. Combobox.Items.Clear causes the cursor position to reset.
        foreach(string Element in ComboxBoxItems)
            comboBox1.Items.Remove(Element);

        //Re-adds all the element in order.
        comboBox1.Items.AddRange(UpdatedComboBoxItems);
    }

С набором тестов {"one", "two", "three"} это выходные данные относительно строки поиска:

  • "o": {"один", "два"}
  • "е": {"один", "три"}
  • "": {"один", "два", "три"}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...