Pepe
Pepe

Reputation: 67

Search by DisplayMember in ListBox

I have a ListBox which I populate like this:

var dtCustomers = db.GetTableBySQL(query).AsEnumerable().Select(rows => 
    new CustomersModel
    {
        Name = rows.Field<string>("Name"),
        ProjectKey = rows.Field<int>("ProjectKey")
    });

lstCustomers.DataSource = dtCustomers.ToList();
lstCustomers.DisplayMember = "Name";
lstCustomers.ValueMember = "ProjectKey";
lstCustomers.ClearSelected();

Now I want to create TextBox with search button to look inside this list and search by item selected as:

private void btnSearch_Click(object sender, EventArgs e)
{
    lstCustomers.SelectedItems.Clear();

    for (int i = lstCustomers.Items.Count - 1; i >= 0; i--)
    {
        if (lstCustomers.Items[i].ToString().ToLower().Contains(txtSearch.Text.ToLower()))
        {
            lstCustomers.SetSelected(i, true);
        }
    }

    lblitems.Text = lstCustomers.SelectedItems.Count.ToString() + "items found";
}

Problem is it never finds anything. I think it is because it is comparing by ValueMember instead of DisplayMember. Can I search in the list by DisplayMember?

Upvotes: 0

Views: 84

Answers (1)

Parrish Husband
Parrish Husband

Reputation: 3178

You can use pattern matching for this since the underlying items will be your CustomersModel:

private void btnSearch_Click(object sender, EventArgs e)
{
    lstCustomers.SelectedItems.Clear();

    int matchCount = 0;
    for (int i = lstCustomers.Items.Count - 1; i >= 0; i--)
    {
        if (lstCustomers.Items[i] is CustomersModel customer &&
            customer.Name.IndexOf(txtSearch.Text, StringComparison.OrdinalIgnoreCase) > -1)
        {
            matchCount++;
            lstCustomers.SetSelected(i, true);
        }         
    }

    lblItems.Text =  $"{matchCount} item{(matchCount > 1 ? "s" : "")} found";
}

Upvotes: 1

Related Questions