Kulahan
Kulahan

Reputation: 522

Multiple Switch statements with multiple cases?

I'm trying to write a switch statement that would have a similar effect to what I show in the code below, but (obviously), it's not working. It will be impossible to have something selected in both combo boxes at once. Any thoughts on how to accomplish this? I'm updating an older program, and I'm trying not to re-write a large chunk of the code.

    switch ((cboMAIN.SelectedIndex) || (cboMAINalternate.SelectedIndex))
            {
                case 0:
                    OutputString1 = "A";
                    break;
                case 1:
                    OutputString1 = "C";
                    break;
                case 2:
                    OutputString1 = "E";
                    break;
                case 3:
                    OutputString1 = "F";
                    break;
                case 4:
                    OutputString1 = "I";
                    break;
                case 5:
                    OutputString1 = "J";
                    break;
                case 6:
                    OutputString1 = "K";
                    break;
            }

Upvotes: 0

Views: 766

Answers (5)

ΩmegaMan
ΩmegaMan

Reputation: 31721

Try using

switch ((cboMAIN.SelectedIndex > -1) ? cboMAIN.SelectedIndex : cboMAINalternate.SelectedIndex) 
{

Upvotes: 2

Matthew Steven Monkan
Matthew Steven Monkan

Reputation: 9160

According to MSDN, SelectedIndex will return -1 if the selection is empty on a ComboBox.

The following code should choose a ComboBox with a selection and go through your switch statement, or fail if neither has a selection:

ComboBox comboBoxToUse;

if (cboMAIN.SelectedIndex > -1)
{
    comboBoxToUse = cboMAIN;
}
else if (cboMAINalternate.SelectedIndex > -1)
{
    comboBoxToUse = cboMAINalternate;
}
else
{
    throw new InvalidOperationException("Neither combo box contains a selection.");
}

switch (comboBoxToUse.SelectedIndex)
{
    ...
}

You may also want to throw an exception if both ComboBoxes have a selection.

Upvotes: 0

Douglas
Douglas

Reputation: 54917

Probably the concisest way:

switch (Math.Max(cboMAIN.SelectedIndex, cboMAINalternate.SelectedIndex))
{
    // ...
}

Upvotes: 0

Guffa
Guffa

Reputation: 700840

There is always a selected item in a select element, so you have to check for the one that you consider to be no selecton, for example the first item:

var item = cboMAIN.SelectedIndex;
if (item = 0) item = cboMAINalternate.SelectedIndex;

switch (item) {
  ...

Upvotes: 0

Mario
Mario

Reputation: 36567

No, that's not possible (at least not the way you're doing it).

The question would be, what are you trying to achieve? If you'd have some kind of toggle to switch between both indexes, you could do something like that:

bool useAlternative = ...;
switch(useAlternative ? cboMAINalternate.SelectedIndex : cboMAIN.Selectedindex) {
    // ...
}

Upvotes: 1

Related Questions