根据C#中的文本框条目显示列表框项

时间:2016-07-15 07:34:51

标签: c#

我只想问一下,一旦用户开始在文本框中输入,是否可以开始在列表框中显示选项(对于在文本框中输入的文本)?

感谢。

1 个答案:

答案 0 :(得分:2)

可能你正在寻找这样的东西:

  • ListBox放在表单(myListBox
  • TextBoxmyTextBox置于下方的实施中)
  • 为文本框
  • 实施TextChanged事件处理程序

可能的实施

// When TextBox's Text changed
private void myTextBox_TextChanged(object sender, EventArgs e) {
  string textToFind = (sender as Control).Text;

  // Do all the changes in one go in order to prevent re-drawing (and blinking)
  myListBox.BeginUpdate();

  try {
    myListBox.SelectedIndices.Clear();

    // We don't want selecting anything on empty 
    if (string.IsNullOrEmpty(textToFind))
      return;

    for (int i = 0; i < myListBox.Items.Count; ++i) {
      string actual = myListBox.Items[i].ToString();

      // Now we should compare two strings; there're many ways to do this 
      // as an example let's select the item(s) which start(s) from the text entered, 
      // case insensitive
      if (actual.StartsWith(textToFind, StringComparison.InvariantCultureIgnoreCase)) {
        myListBox.SelectedIndices.Add(i);

        // can we select more than one item == shall we proceed?
        if (myListBox.SelectionMode == SelectionMode.One)
          break;
      }
    }
  }
  finally {
    myListBox.EndUpdate();
  }
}