【问题标题】:Search an item in the listbox where the item to be searched is in textbox and no button click C#在列表框中搜索要搜索的项目在文本框中的项目,并且没有按钮单击 C#
【发布时间】:2013-03-03 08:07:22
【问题描述】:

说我有一个列表框,其中的项目已经存在,说项目是

Ant
Adam    
Ball
Cat
Dog
Ear
Frog

在列表框上方有一个文本框提示用户搜索

说如果我输入文本框 ad 那么它必须指向 Adam 如果我删除 a 那么它必须指向 Dog 并且不得使用按钮进行搜索

如果我点击列表框中的项目 cat,然后在列表框旁边有一个文本框,上面写着 Hi I'm Cat

我发现使用文本框显示嗨,我是猫是不正确的,我应该使用什么来显示有关所选项目详细信息的信息。

自己找到解决方案

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        int index = listBox1.FindString(textBox1.Text, -1);
        if (index != -1)
        {
            listBox1.SetSelected(index, true);
        }
    }

【问题讨论】:

  • 找到解决方案 my self private void textBox1_TextChanged(object sender, EventArgs e) { int index = listBox1.FindString(textBox1.Text, -1); if (index != -1) { listBox1.SetSelected(index, true); } }

标签: c# .net winforms listbox windows-forms-designer


【解决方案1】:

您需要在 TextBox 的“TextChanged”事件上更新您的列表框。

获取该事件内文本框中写入的文本,遍历列表框的项目并执行Text.Contains

protected void TextBox1_TextChanged(object sender, EventArgs e)
        {
            var current = TextBox1.Text;
            foreach (ListItem item in ListBox1.Items)
            {
                if (item.Text.ToLower().Contains(current.ToLower()))
                    item.Selected = true;
            }
        }

这是获取列表框选定项的方法:

protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(ListBox1.SelectedItem!=null)
            {
               Label1.Text =  ListBox1.SelectedItem.Text;
               //or you can dynamically create a label and add it to the page
               Label lbl = new Label();
               lbl.Text=ListBox1.SelectedItem.Text;
               MyContainer.Controls.Add(lbl);
               //where MyContainer is any server side container, HtmlContainerControl  
               //or HtmlControl 
            }
        }

【讨论】:

  • 你需要使用 System.Web.UI.WebControls 添加;到你的页面
  • 我找不到命名空间。 k 离开它。在单击列表框项目时,将显示带有所选项目文本的标签。如何做到这一点。
  • ListBox 有一个偶数“SelectedIndexChanged”,您可以使用它来执行您想要的任何额外逻辑。我正在更新我的答案
【解决方案2】:

它必须是一个列表框吗?如果您改用 ComboBox,则可以使用自动完成功能。例如,将 AutoCompleteMode 设置为“SuggestAppend”,将 AutoCompleteSource 设置为“ListItems”。列表框没有内置该功能,因此您必须自己实现它。

另外,对于它旁边的标签或文本框来说,“嗨,我是猫”.. 或其他.. 使用 SelectedIndexChanged 事件。在那里你可以做这样的事情:

myLabel.Text = "Hi, I'm " + myComboBox.SelectedItem.ToString()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    • 2017-02-16
    • 1970-01-01
    相关资源
    最近更新 更多