Reputation: 57
The comboBox9 gets populated with unique values from an Excel Range with the code below.
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);
}
What i tried to do unsuccessfully is set the index of the combobox9 with the first item that satisfies the if condition .
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);
}
}
Any ideas on where i'm going wrong ?
Upvotes: 0
Views: 771
Reputation: 2164
I think your code might get an exception of "Specified cast is not valid" in the line of
comboBox9.SelectedIndex = comboBox9.Items.IndexOf(item);
because you are adding the items in comboBox9 as "string" type and using "int" type in foreach (int item in comboBox9.Items)
. So, Please Check your code. I am going to paste 2 different codes below both for int type and string type.
//FOR INT TYPE
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);
}
}
}
//FOR String Type
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);
}
}
}
NOTE: Both codes are works fine in Winforms Application. Please check and try it.
Upvotes: 1
Reputation: 57
Figured it out :
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;
}
Upvotes: 0
Reputation: 7610
All items match the condition will be selected. Because the selection unique, the last selected item is displayed.
When the first item is selected, you need stop the selection :
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
}
}
Upvotes: 1