使用索引搜索列表框中的项目

时间:2013-02-06 04:34:29

标签: c# winforms listbox

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

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;
            }
        }

4 个答案:

答案 0 :(得分:4)

尝试这样的操作,在按钮中添加点击事件并将代码放入其中。这对我有用。

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

答案 1 :(得分:2)

不确定你要做什么,但这里有一些样品 此外,开始给变量有用的名称。如果您在一个月内回到此代码,您将不知道那里发生了什么或textBox6是什么。

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

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);

答案 2 :(得分:0)

你可以用字符串

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

        }

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

答案 3 :(得分:-1)

private void button1_Click(object sender, System.EventArgs e)
{
    if (listBox1.FindString("Your String in Textbox 6") != -1)
     {
        MessageBox.Show("Success!");
     }
}