views:

689

answers:

2

I have a ASP.NET webform that, aside from other controls, has a textbox for entering a value, a textbox to display values, a dropdownlistbox, and a search button. I am using the following code to display search results:

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

The DDL3 gets its values from a DataTable, and the value entered into TextBox3 should match one of the DDL3 values to display the search results after the search button is clicked. The NullReferenceException error occurs when the TextBox3 value is either null or does not match any value in DDL3. This is reasonable; however, I have spent a few hours trying to handle this error and I cannot seem to figure out how to go about it. I have tried to add additional "If" statements, such as "if TextBox3 == null, etc...; however, to no avail. How should I change the above if statement to compensate for a null value or a wrong value?

Thank you,

DFM

+1  A: 

Try using a try...catch on that exception:

try {
    TextBox3.text = DropDownList3.Items.FindByText(TextBox3.Text).Value
} catch (NullReferenceException ex) {
    TextBox3.text = "(none)";
}
Lloyd
Thank you for the response - I tried the above solution; however, I am getting an error due to the "e" after the NullReferenceException. I cannot declare "e" since it is used for my EventArgs.
Although I get the error, your solution works; thank you. I'll have to figure out the other error; however, the event fires properly.
just change it to ex
John Nolan
+1  A: 

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

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

Scott Ivey
Thanks for the repsonse - the item does exist in the DDL, prior to the if statement. I did try your example before posting this question, and the code would skip the != and go to the next if statement, the statement in question, which will then give me the error.