如何在C# Windows Forms中设置ComboBox的选定项?

12

我想在DataGrid的点击事件中设置comboBox的选定项,但是我无法做到。我已经进行了谷歌搜索并尝试了不同的方法,但没有成功。

对我来说,SelectedIndex是有效的,但我找不到ComboBox中项目的索引,因此无法选择该项目。

代码示例:

for (int i = 0; i < cmbVendor.Items.Count; i++)

    if (cmbVendor.Items[i].ToString() == Convert.ToString(gridView1.GetFocusedRowCellValue("vVendor")))
    {
        cmbVendor.SelectedIndex = i;
        break;
    }

你尝试过将.Text/.Value(我记不清ComboBox使用哪一个)设置为你想要选择的项目吗? - Marvin Smit
使用一个包含id、value(任何主键)的类列表来填充组合框数据源,然后使用SelectedValue属性:cmbVendor.SelectedValue。 - Amen Ayach
如果获取的值为true并且selectedIndex存在问题,那么if语句是否总是false? - Akrem
2
GetFocusedRowCellValue() 不是 DataGrid 的一个方法。如果您使用另一个供应商的网格控件或使用扩展方法,则必须在问题中记录该信息。 - Hans Passant
10个回答

15

1
抱歉,不起作用...indexOf返回-1,即使GridView提供了当前字符串。 - Azhar
这里有些问题:gridView1.GetFocusedRowCellValue("vVendor"). - Kamil

13

以下内容对我完美运作。传递任何在组合框中可用的值或文本。

comboBox1.SelectedIndex = comboBox1.FindString(<combobox value OR Text in string formate>);

5
你的if语句中已经包含了它:
cmbVendor.SelectedItem = cmbVendor.Items[i];

1
不再需要循环,可以直接将.SelectedItem设置为'Convert.ToString(gridView1.GetFocusedRowCellValue("vVendor"))'。 - Marvin Smit
抱歉,不起作用...实际上它并没有通过if语句。 - Azhar

3
最后我找到了。它是:


cmbVendor.Text = Convert.ToString(gridView1.GetFocusedRowCellValue("vVendor"));

SelectedText属性用于组合框文本框部分中可编辑文本的选定部分。


2

如果您已经为ComboBox控件设置了ValueMember属性,您可以直接将值分配给ComboBox控件的SelectedValue属性。您不需要显式地查找索引。

以下是一个示例:

public class Vendor{
    public int VendorId {get; set;}
    public string VendorName {get; set;}
}

// Inside your function
   var comboboxData = new List<Vendor>(){
       new Vendor(){ vendorId = 1, vendorName = "Vendor1" },
       new Vendor(){ vendorId = 2, vendorName = "Vendor2" }
   }

   cmbVendor.DataSource = comboboxData;
   cmbVendor.DisplayMember = "VendorName";
   cmbVendor.ValueMember = "ValueId";

// Now, to change your selected index to the ComboBox item with ValueId of 2, you can simply do:
   cmbVendor.SelectedValue = 2;

使用这种方法选择项目很好。然而,当通过执行cmb.DroppedDown=true;显示列表时,没有任何答案实际上会突出显示所选项目。 - gridtrak

1
假设 gridView1.GetFocusedRowCellValue("vVendor") 的确按预期工作,下面的代码应该可以解决问题。
string selected = Convert.ToString(gridView1.GetFocusedRowCellValue("vVendor"));
foreach ( var item in cmbVendor.Items )
{
    if (string.Compare(item.ToString(), selected, StringComparison.OrdinalIgnoreCase) == 0)
    {
        cmbVendor.SelectedItem = item;
        break;
    }
}

原始代码多次调用了gridView1.GetFocusedRowCellValue("vVendor"),而您只需要调用一次。

建议的"comboBox1.Items.IndexOf("对于cmbVendor.Items的内容做出了太多假设。


0
ComboBox1.SelectedIndex= ComboBox1.FindString("Matching String From DataGrid Cell value")

在 C# Windows 应用程序中尝试这个,它会很好地工作。


0

我曾经遇到过类似的问题,并在这里其他答案的帮助下部分解决了它。首先,我的特定问题是

combobox1.SelectedItem = myItem;

不按预期工作。根本原因是myItem是来自一个组的对象,这个组与combobox中的项目实际上是相同的列表,但是它实际上是这些项目的副本。因此,myItem与有效条目完全相同,但本身不是来自combobox1容器的有效对象。

解决方案是使用SelectedIndex而不是SelectedItem,像这样:

combobox1.SelectedIndex = get_combobox_index(myItem);

在哪里

    private int get_combobox_index(ItemClass myItem)
    {
        int i = 0;
        var lst = combobox1.Items.Cast<ItemClass >();
        foreach (var s in lst)
        {
            if (s.Id == myItem.Id)
                return i;

            i++;
        }
        return 0;
    }

0

我知道这是一个非常老的问题,但是我想加上我的0.02,因为最近我遇到了类似的问题,当尝试在Form_Load时初始化绑定到数据源的C# WinForms ComboBox并选择特定选项时。在这种情况下,我发现使用绑定源本身(通过BindingSource类)将所选项目设置为更好的解决方案,而不是使用任何ComboBox的Selected[...]方法。后者调用无法选择我希望用户看到的默认值。

以下是对我有效的代码(例如在Form_Load中尝试此代码):

// Let's say my datasource is a sorted dictionary for the sake of example
SortedDictionary<int, string> dataSource = new SortedDictionary<int, string>();            

// < Code where your datasource is built or retrieved >

// Data index that I want selected in my combobox
int iDataSourceItemIndex = 2; // Arbitrary index value that I know exists...

// Use a binding source instance before adding your datasource to the combobox
BindingSource bindingSource = new BindingSource(dataSource, null);

// The item selection occurs here!
bindingSource.Position = iDataSourceItemIndex;

// Create and bind the combobox to its datasource, with implicit selected index
ComboBox comboBox1 = new ComboBox();

comboBox1.Name = "MyCombo1";
comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
comboBox1.DataSource = bindingSource;

Controls.Add(comboBox1);

-1

这对我来说很有效......

string displayMember = ComboBox.DataSource.To<DataTable>().Select("valueMemberColumn = '" + value + "'")[0]["displayMember"].ToString();
ComboBox.FindItemExact(displayMember, true).Selected = true;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接