【问题标题】:How to fix displayMember?如何修复显示成员?
【发布时间】:2019-08-13 06:44:29
【问题描述】:

我正在开发一个应用程序,需要使用包含而不是 StartsWith 来搜索组合框,无法绑定显示成员。

试图将它直接绑定到类,但没有运气。

    private void customersDropDown_TextUpdate(object sender, EventArgs e)
    {
        var company = (NMA0701R)companyDropDown.SelectedItem;
        var items = priceCalculatorContext.GetCustomers(company.CompanyNumber, 0);
        List<string> stringList = items.Select(i => i.ToString()).ToList();

        string filter_param = customersDropDown.Text;
        List<string> filteredItems = stringList.FindAll(x => x.ToLower().Contains(filter_param.ToLower()));

        customersDropDown.DisplayMember = "FullCustomer";
        customersDropDown.ValueMember = "CustomerNumber";
        customersDropDown.DataSource = filteredItems;

        if (String.IsNullOrWhiteSpace(filter_param))
        {
            customersDropDown.DataSource = items;
        }
        customersDropDown.DroppedDown = true;
        Cursor.Current = Cursors.Default;

        // this will ensure that the drop down is as long as the list
        customersDropDown.IntegralHeight = true;

        // remove automatically selected first item
        customersDropDown.SelectedIndex = -1;

        customersDropDown.Text = filter_param;

        // set the position of the cursor
        customersDropDown.SelectionStart = filter_param.Length;
        customersDropDown.SelectionLength = 0;
    }

我已使用此答案尝试让我的代码正常工作:https://stackoverflow.com/a/40990757/11707295 我希望能够进行包含搜索而不是 StartsWith。

【问题讨论】:

    标签: c# winforms combobox


    【解决方案1】:

    组合框的DisplayMemberValueMember 属性需要您在数据源中绑定的属性的字符串名称。

    因此,在您的示例中,将 DisplayMember 设置为“FullCustomer”并将 ValueMember 设置为“CustomerNumber”意味着您希望您的数据源是客户对象的列表。但是您将数据源设置为字符串对象列表。

    另外,这一行:

    List<string> stringList = items.Select(i => i.ToString()).ToList();
    

    正在尝试将客户对象转换为不正确的字符串。

    你可以直接使用 items 变量:

            var items = priceCalculatorContext.GetCustomers(company.CompanyNumber, 0);
            string filter_param = comboBox1.Text.ToLower();
            var filteredList = items.ToList().FindAll(x => x.FullCustomer.ToLower().Contains(filter_param));
    
            comboBox1.DisplayMember = "FullCustomer";
            comboBox1.ValueMember = "CustomerNumber";
    
    
            if (filteredList.Count() > 0)
                comboBox1.DataSource = filteredList;
    
            //set the datasource to items if the filter is empty, or the filtered list is empty
            if (String.IsNullOrWhiteSpace(filter_param) || filteredList.Count() == 0)
            {
                comboBox1.DataSource = items;
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-21
      • 2020-04-25
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 2014-09-23
      相关资源
      最近更新 更多