Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在列表框中按DisplayMember搜索_C#_Winforms - Fatal编程技术网

C# 在列表框中按DisplayMember搜索

C# 在列表框中按DisplayMember搜索,c#,winforms,C#,Winforms,我有一个列表框,我这样填充: var dtCustomers = db.GetTableBySQL(query).AsEnumerable().Select(rows => new CustomersModel { Name = rows.Field<string>("Name"), ProjectKey = rows.Field<int>("ProjectKey") }); lstCustomers.Da

我有一个列表框,我这样填充:

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

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

您可以对此使用模式匹配,因为基础项将是您的CustomerModel:

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