NullReferenceException error in ASP.NET with C # - trying to handle error

I have an ASP.NET Web Form that, among other controls, has a text box to enter a value, a text box to display values, a dropdownlistbox, and a search button. I use the following code to display search results:

if (TextBox3.text == DropDownList3.Items.FindByText(TextBox3.Text).Value) 
{
  etc... 
}

      

DDL3 gets its values ​​from the DataTable, and the value entered in TextBox3 must match one of the DDL3 values ​​to display the search results after the search button is clicked. A NullReferenceException error is thrown when the value of TextBox3 is null or does not match any value in DDL3. It is reasonable; however I have spent several hours trying to deal with this error and I cannot figure out how to do it. I tried adding additional "If" statements like "if TextBox3 == null, etc." but to no avail. How do I modify the above if statement to compensate for a null value or an invalid value?

Thanks,

DFM

0


a source to share


2 answers


Try using try ... catch on this exception:



try {
    TextBox3.text = DropDownList3.Items.FindByText(TextBox3.Text).Value
} catch (NullReferenceException ex) {
    TextBox3.text = "(none)";
}

      

+2


a source


you should check if the item exists in the list before checking its value.



if (DropDownList3.Items.FindByText(TextBox3.Text) != null)
{
   // ...
}

      

+1


a source







All Articles