【问题标题】:displaying listbox items according to textbox entry in C#根据 C# 中的文本框条目显示列表框项
【发布时间】:2016-07-15 07:34:50
【问题描述】:

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

谢谢。

【问题讨论】:

  • 简答:有可能;如果你想继续问,说,“我怎样才能实现这样的例程?”您必须提供更多详细信息(WinForms/WPF、您的尝试等)
  • @DmirtyBychenko 谢谢你的简短回答。它是一个 Windows 窗体,到目前为止我还没有尝试过任何这样的东西。实际上,我无法弄清楚如何进行。如果我得到它的参考链接会很棒。谢谢。

标签: c#


【解决方案1】:

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

  • 在表格中输入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();
  }
}

【讨论】:

  • 谢谢。对如何进行有一个想法。 :)
猜你喜欢
  • 1970-01-01
  • 2016-03-08
  • 1970-01-01
  • 2014-09-28
  • 2017-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多