根据条件设置组合框选定的索引/项目



comboBox9 使用以下代码填充了 Excel Range 中的唯一值。

comboBox9.Items.Clear();
HashSet<string> distinct = new HashSet<string>();

foreach (_Excel.Range cell in range.Cells)
{
string value = (cell.Value2).ToString();
if (distinct.Add(value))
comboBox9.Items.Add(value);
}

我尝试做的不成功是使用满足 if 条件的第一项设置 combobox9 的索引。

foreach (string item in comboBox9.Items)
{
if (278 * Variables.m3h / (Math.Pow(int.parse(item) / 2, 2) * 3.14) > Variables.maxvelocity)
{
comboBox9.SelectedIndex = comboBox9.Items.IndexOf(item);
}
}

关于我哪里出错的任何想法?

将选择所有符合条件的项目。由于所选内容是唯一的,因此将显示最后选定的项目。

选择第一项时,您需要停止选择:

foreach (int item in comboBox9.Items)
{
if (278 * Variables.m3h / (Math.Pow(item / 2, 2) * 3.14) > Variables.maxvelocity)
{
comboBox9.SelectedIndex = comboBox9.Items.IndexOf(item);
break; // a item is selected, then stop the selection
}
}

我认为您的代码可能会在以下行中出现"指定的强制转换无效"的异常

comboBox9.SelectedIndex = comboBox9.Items.IndexOf(item);是因为您将 comboBox9 中的项目添加为"字符串"类型并在foreach (int item in comboBox9.Items)中使用"int"类型。因此,请检查您的代码。我将在下面粘贴 2 个不同的代码,用于 int 类型和字符串类型。
//对于 int 类型

void ComboLoadAndSelectIndex()
{
comboBox9.Items.Add(1);
comboBox9.Items.Add(10);
comboBox9.Items.Add(20);

foreach (int item in comboBox9.Items)
{
if (item == 10)//your math Condition
{
comboBox9.SelectedIndex = comboBox9.Items.IndexOf(item);
}

}
}

字符串类型

void ComboLoadAndSelectIndex()
{
comboBox9.Items.Add(1.ToString());
comboBox9.Items.Add(10.ToString());
comboBox9.Items.Add(20.ToString());
foreach (string item in comboBox9.Items)
{
if (item == 10.ToString())//your math Condition
{
comboBox9.SelectedIndex = comboBox9.Items.IndexOf(item);
}
}
}

注意:这两个代码在Winforms应用程序中都可以正常工作。请检查并尝试一下。

想通了:

comboBox9.Items.Clear();
HashSet<string> distinct = new HashSet<string>();

foreach (_Excel.Range cell in range.Cells)
{
string value = (cell.Value2).ToString();
if (distinct.Add(value))
comboBox9.Items.Add(value);
}
if (comboBox9.Items.Count > 1)
{
foreach (string item in comboBox9.Items)
{
if (278 * Variables.m3h / (Math.Pow(int.Parse(item) / 2, 2) * 
3.14) < Variables.maxvelocity)
{
comboBox9.SelectedIndex = comboBox9.Items.IndexOf(item);
break;
}
}
}
else
{
comboBox9.SelectedIndex = -1;
}

最新更新