C#在ListBox1中搜索项目

时间:2018-05-16 21:58:06

标签: c# search listbox

我想通过TextBox4在ListBox1中执行搜索项。 此视频中的示例 - 倒带时间7.20 https://www.youtube.com/watch?v=7J-D4OzfX7Y; 但我没有dataBase。我有一个用于存储数据的类。 我不知道如何进行搜索以找到我需要的项目。档案 - http://dropmefiles.com/bVrnXForeach - Error, could not convert char type to stringClassForm1SeeForm2。如果不使您复杂化,可以在TextBox4上编写代码吗?我写错了TextBox4代码,所以请更正

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        if (Properties.Settings.Default.Accounts == null)
            Properties.Settings.Default.Accounts = new List<Account>();

        if (Properties.Settings.Default.Accounts != null)
        {
       foreach (var account in Properties.Settings.Default.Accounts)
            {
                listBox1.Items.Add(account);
            }
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        new Form2(listBox1).Show();
    }

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }



    private void textBox4_TextChanged(object sender, EventArgs e)
    {
        if (Properties.Settings.Default.Accounts != null)
        {
            foreach (var account in Properties.Settings.Default.Accounts)
            {


                var registrationsList = account.Name;


                listBox1.BeginUpdate();
                listBox1.Items.Clear();

                if (!string.IsNullOrEmpty(textBox4.Text))
                {
                    foreach (string str in registrationsList)
                    {
                        if (str.Contains(textBox4.Text))
                        {
                            listBox1.Items.Add(str);
                        }
                    }
                }
                else
                    listBox1.Items.Add(account); //there is no any filter string, so add all data we have in Store

                listBox1.EndUpdate();
            }
        }
    }


}

1 个答案:

答案 0 :(得分:0)

您无法将图表类型转换为字符串异常,因为您在Account.Name字符串本身上调用foreach,它会遍历帐户名称中的每个字符。我已经重写了方法来正确更新listBox1以获取过滤器字符串。

private void textBox4_TextChanged(object sender, EventArgs e)
{
    if (Properties.Settings.Default.Accounts != null)
    {
        listBox1.BeginUpdate();
        listBox1.Items.Clear();
        if (!String.IsNullOrEmpty(textBox4.Text))
        {
            foreach (var account in Properties.Settings.Default.Accounts)
            {
                if (account.Name.Contains(textBox4.Text))
                {
                    listBox1.Items.Add(account);
                }
            }

        }
        else //there is no any filter string, so add all data we have in Store
        {
            foreach (var account in Properties.Settings.Default.Accounts)
            {
                listBox1.Items.Add(account);
            }
        }

        listBox1.EndUpdate();
    }
}