在列表框中按DisplayMember搜索

时间:2018-09-03 22:39:16

标签: c# winforms

我有一个ListBox,我是这样填充的:

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

现在,我要创建带有搜索按钮的TextBox,以在此列表中查找并按以下项进行搜索:

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

问题是它什么也找不到。我认为这是因为它是通过ValueMember而不是DisplayMember进行比较的。我可以按DisplayMember在列表中搜索吗?

1 个答案:

答案 0 :(得分:1)

您可以为此使用模式匹配,因为基础项将是您的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";
}