Search code examples
c#asp.netvisual-studioradiobuttonlist

NullException Error in RadioButtonList when no value is selected


I am trying to find a way to throw an error when user doesn't select a value in dropdown list. I tried many solutions, that were provided here. But none seem to work.This is my code

protected void Button1_Click(object sender, EventArgs e)
   {
       if (RadioButtonList1.SelectedItem.Value == null)
            {
              //Throw error to select some value before button click
            } 

       if (RadioButtonList1.SelectedItem.Value == 'male')
           {
              //Step1
           }
       if (RadioButtonList1.SelectedItem.Value == 'female')
           {
              //Step2
           }
    }

tried replacing with

 if (RadioButtonList1.SelectedIndex == -1)

But that too did not work. Any ideas?


Solution

  • It will be easier for you to debug if selected item is put into variable:

    var selectedItem = RadioButtonList1.SelectedItem;
    if (selectedItem == null)
    {
        throw new Exception("Please select");
    } 
    else if (selectedItem.Value == "male")
    {
        // step 1
    }
    

    Radio buttons are specific. If nothing is selected, there is no selectedItem, thus no value of an object which doesn't exist.

    Edit: place debugger point in first line, var selectedItem =.. so you will on hover know what exact value it has.

    Edit2: ALWAYS check if your object is not null. Your error in the comment is caused by the fact that you immediately try to access of an object property when actual object doesn't exist.