Takarii
Takarii

Reputation: 1648

Shorter method for checking ComboBoxItem has been selected

I have a large number of ComboBoxes in my application. They all need to start blank, so their default selected index is always set to -1 and the boxes are prepopulated with hardcoded choices. Some of the boxes aren't required to have an item selected when the form is submitted, so are allowed to remain blank (and stay at an index of -1).

Currently Im using the following to check if an item is selected, and assign its content value if it has.

if (ComboBox.SelectedIndex >= 0)
{
    MyObject.Val1 = ((ComboBoxItem)ComboBox.Items[ComboBox.SelectedIndex]).Content.ToString();
}

Obviously I can't simply use

((ComboBoxItem)ComboBox.Items[ComboBox.SelectedIndex]).Content.ToString();

on its own in case no value has been selected as it will throw an ArgumentOutOfRangeException

Is there a more elegant way to do this, or am I stuck to running this qualifier every time I need to?

Edit:

I did have an idea using a function like so

public string ComboChecker(ComboBox box, int index)
{
    if (index >= 0)
    {
        return ((ComboBoxItem)box.Items[box.SelectedIndex]).Content.ToString();
    }
    else
    {
        return "";
    }
}

That way I would only need to do MyObject.Val = ComboCheck(ComboBox,ComboBox.SelectedIndex) each time instead

Upvotes: 0

Views: 55

Answers (1)

Dai
Dai

Reputation: 155045

public static void GetSelectedValue(ComboBox c, Action<String> gotValue) {
    if( c.SelectedIndex >= 0 ) {
        ComboBoxItem item = c.Items[ c.SelectedIndex ];
        gotValue( item.Content.ToString() );
    }
}

Usage:

GetSelectedValue( MyComboBox, v => MyObject.Val1 = v );

Upvotes: 2

Related Questions