Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

c# - Set combobox selected index/item according to a condition

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 ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...