可变组合框的 SelectedItem

SelectedItem of a variable combobox

有一个组合框,我用这个循环填充

foreach (Machine.Types machine in machineList)
{
    cbMachineGUI.Items.Add(machine);
}

之后我希望选定的索引是一台特定的机器。

string machineComboBox = SettingsManager.getParameter("MachineType");
cbMachineGUI.SelectedItem = machineComboBox;

参数设置正确,但是combobox的selecteditem一直没有。

如果我在组合框的属性中设置机器(不是通过循环),它就可以工作。但我需要组合框可变。

有什么建议吗?

我建议您不要设置 SelectedItem,而是找到项目的索引并设置选定的索引。

像这样:

string machineComboBox = SettingsManager.getParameter("MachineType");
int itemIndex = cbMachineGUI.Items.IndexOf(machineComboBox);
cbMachineGUI.SelectedIndex = itemIndex;

您可以尝试以下方法:

cbMachineGUI.SelectedIndex = cbMachineGUI.Items.IndexOf("MachineType"); // or whatever you want to select

您尝试设置的项目可能没有出现在组合框项目列表中,并且由于您实际上没有选择任何内容,因此它设置为空。要检查该项目是否存在,请执行以下操作

string machineComboBox = SettingsManager.getParameter("MachineType");
if(cbMachineGUI.Items.IndexOf(machineComboBox) >= 0)
 cbMachineGUI.SelectedItem = machineComboBox;

引自 MSDN 文档:

When you try to set the SelectedItem property to an object, the ComboBox attempts to make that object the currently selected one in the list. If the object is found in the list, it is displayed in the edit portion of the ComboBox and the SelectedIndex property is set to the corresponding index. If the object does not exist in the list, the SelectedIndex property is left at its current value.The ComboBox class searches for the specified object by using the IndexOf method.

查看 ComboBox.SelectedItem 了解更多信息。

问题是你在Items中设置的和你在SelectedItem中设置的是不同的类型。

您正在用 Machine.Types 个实例填充 Items 集合,并将 SelectedItem 设置为 string 个实例。

像其他答案建议的那样使用 IndexOf 将无济于事,因为这不会做设置 SelectedItem 尚未做的任何事情。它仍然不会在 Items 集合中找到 machineComboBox,就像现在找不到一样。

您需要使用匹配类型,所以 其中一个(取决于您如何使用组合框中的值):

  1. 填充集合时将Machine.Types转换为string

    cbMachineGUI.Items.Add(machine.ToString());
    
  2. machineComboBox 转换为 Machine.Types 的实例,在设置 SelectedItem 时将匹配 Items 中的实例 - 如何执行取决于Machine.Types 是什么

  3. 设置时自己找到正确的项目SelectedItem:

    cbMachineGUI.SelectedItem = cbMachineGUI.Items
                                            .OfType<Machine.Types>()
                                            .FirstOrDefault(item => item.ToString() == machineComboBox);
    

无论哪种方式,您都必须在这两种类型之间进行转换某处