【问题标题】:Search items in the listbox using index使用索引在列表框中搜索项目
【发布时间】:2016-09-13 05:31:34
【问题描述】:

我正在做一个使用列表框的项目,我可以添加项目、删除项目、更新项目但我无法搜索, 这是我的搜索代码

string search = Person.listperson[listBox1.SelectedIndex].lastname;
            foreach (String s in search)
            {
                if (s.Equals(textBox6.Text))
                {
                     //show searched items
                    MessageBox.Show("Success!");
                }
            }

你能帮我解决这个问题吗? 谢谢:)

我这里有一个搜索代码, 但它不适用于按钮,我怎样才能将它应用到按钮上?

private void textBox6_TextChanged(object sender, EventArgs e)
        {
            int index = listBox1.FindString(this.textBox6.Text);
            if (0 <= index)
            {
                listBox1.SelectedIndex = index;
            }
        }

【问题讨论】:

  • 我想,我不能使用'foreach' :(
  • 什么是 Person.listperson 是另一个列表框吗?我对你在做什么有点困惑。看起来您正在 listBox1 中选择一个项目,然后使用它的索引从Something中选择一个姓氏?它只给你一个不实现 IEnumerable 的字符串,所以你不能使用 foreach。
  • 这是我的搜索代码:D

标签: c# winforms listbox


【解决方案1】:

尝试这样的事情,为您的按钮添加一个点击事件并将您的代码放入其中。这对我有用。

private void button1_Click(object sender, EventArgs e)
{
    int index = listBox1.FindString(textBox6.Text);
    if (index > -1)
    {
        listBox1.SelectedIndex = index;
    }
}

【讨论】:

  • 我添加了一个点击事件示例,您的代码无论是在 TextChanged 事件还是点击事件中都应该可以工作。
  • 我认为它不适用于按钮
  • 该代码将在按钮单击事件中正常工作。我假设您仍在使用 textBox6 作为搜索字符串的来源。
  • 是的,你的权利,我忘了删除 textbox6 事件中的代码 :)
【解决方案2】:

不确定您到底要做什么,但这里有一些示例。
另外,开始给变量起有用的名字。如果您在一个月后回到这段代码,您将不知道那里发生了什么或textBox6 是什么。

在整个listperson 集合中查找字符串(textBox6):

var list = Person.listperson.Where(p => p.lastname.Contains(textBox6.Text));

检查listperson 中的特定项目是否具有部分textBox6 值:

var search = Person.listperson[listBox1.SelectedIndex].lastname;
bool success = search.Contains(textBox6.Text);

或者如果您想比较这些值:

bool success = (search == textBox6.Text);

【讨论】:

    【解决方案3】:

    你可以在字符串中foreach char

    string s = "Blippy you";
            foreach (char item in s)
            {
    
            }
    

    但是任何人。尝试使用 Text.RegularExpressions 进行字符串匹配。

    【讨论】:

      【解决方案4】:
      private void button1_Click(object sender, System.EventArgs e)
      {
          if (listBox1.FindString("Your String in Textbox 6") != -1)
           {
              MessageBox.Show("Success!");
           }
      }
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-25
      • 2013-12-20
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 2012-04-16
      相关资源
      最近更新 更多