Search code examples
c#exceptioncomboboxbuttonclick

Problems catching an exception in c#


I have a combobox with two items. I also have a button that opens a new form when one of these items are selected. However if none of the items are selected there is an exception(nullpointer). I have tried (to no avail) to catch this exception and show a mbox that prompts the user to choose one of the items.

Here is the code for the button click even:

if (labelGrid.Text == "Member" && cbTable.SelectedItem.ToString().Equals("Workout"))
        {
            string name;
            string ss;
            foreach (DataGridViewRow item in this.dtGrid1.SelectedRows)
            {
                ss = dtGrid1.CurrentCell.Value.ToString();
                name = dtGrid1.SelectedCells[1].Value.ToString();
                BookMemberWorkout bmw = new BookMemberWorkout(ss, name);
                bmw.Label2.Text = ss;
                bmw.Label1.Text = name;
                bmw.ShowDialog();
            }
        }

Solution

  • You are not supposed to use exceptions for flow control in non-exceptional cases. The case that the user didn't select anything is surely not exceptional.

    The correct approach would be a simple null check:

    if(cbTable.SelectedItem == null)
    {
        // Show message box
    }
    else
    {
        // Your current code
    }
    

    Why your exception handling code isn't working is impossible to answer, because you didn't include it in your question.