【问题标题】:How can I set selected in a ComboBox, based on ValueMember?如何根据 ValueMember 在 ComboBox 中设置选择?
【发布时间】:2014-08-04 09:04:53
【问题描述】:

我有一个具有以下结构的组合框。另外,我从另一个来源获得 fld_id ,并且基于该 ID,我需要在 ComboBox 中选择相应的项目。我该怎么做?

comboBoxCustomers.DataSource = customers;

comboBoxCustomers.ValueMember = "fld_id";

comboBoxCustomers.DisplayMember = "fld_name";

例子:

列表可以包含这些项目

fld_id   fld_name

65       Item1

68       Item2

69       Item3

我需要将第 68 项设置为选中。

【问题讨论】:

  • 我从另一个来源获得一个 fld_id 并基于该 id 我需要在 ComboBox 中选择相应的项目,这是什么意思?发布更多代码以显示您如何获得fld_id?那是财产吗?
  • 它来自哪里并不重要。我只需要选择具有该 id 的项目作为 valuemember
  • 当你:var selected = comboBoxCustomers.SelectedValue; 时会发生什么?
  • 其实很重要!如果它是一个属性,您可以使用binding to bind it as shown here。虽然不确定它是否适用于这种情况。
  • 试试这个:comboBoxCustomers.SelectedValue = 68;

标签: c# winforms combobox


【解决方案1】:

使用关注:

comboBoxCustomers.SelectedValue = fld_id(which you are getitng from another source)

【讨论】:

    【解决方案2】:

    我没有足够的声望来发表评论。这个:

    comboBoxCustomers.SelectedValue = fld_id
    

    效果很好 :) 但是 AFTER 显示表单,否则它将失败。

    【讨论】:

      【解决方案3】:

      如果您使用组合框的数据源,您可以将数据源转换回列表,找到项目并使用该项目设置选定项目:

      var stores = cbxStores.DataSource as List<store>;
      var store = stores.Where(w => w.store_code == _station.store_code).FirstOrDefault();
      cbxStores.SelectedItem = store;
      

      【讨论】:

        【解决方案4】:

        我为自己找到的最简单的程序:

        您可以在调用函数时将其绑定到带有参数的函数中。

        希望对大家有所帮助:

        int Idd = Convert.ToInt32(your value for the combobox  you want to be selected);
        for (int i = 0; i < myComboBox.Items.Count; i++)
        {
            myComboBox.SelectedIndex = i;
            if (Convert.ToInt32( myComboBox.SelectedValue ) == Idd )
                {break;}                   
        }
        

        【讨论】:

          猜你喜欢
          • 2023-03-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-12-17
          相关资源
          最近更新 更多