string.isNullOrEmpty(SelectedItem.Value) not work

Hi

I have a drop down list in a aspx form which uses C#.

If I do not choose anything and pressed submit button, it throws nullreference exception.

But, I use the following code to check it in if condition and still not work.

How can I fix it?
string a = this.location.SelectedItem.Value;
if (string.IsNullOrEmpty(this.location.SelectedItem.Value) || this.location.SelectedItem.Value == null || this.location.SelectedItem.Value =="")

Open in new window

techquesAsked:
Who is Participating?
 
David H.H.LeeCommented:
Hi techques,
Try this easier way:

string a = this.location.SelectedItem.Value.toString();
if(a=="")

0
 
tetorvikCommented:
i believe your dropdownlist SelectedItem is null, therefore you'll get the exception. You'll need to check that prior to access it's Value property

if(this.location.SelectedItem != null)
{

}
0
 
techquesAuthor Commented:
both work, thanks for help
0
 
ppittleCommented:
Or try this.location.SelectedValue, which returns a string, so you don't need to check for a null reference, as long as you have a valid pointer to your drop down list
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.