1

I am trying to verify if the SelectedItem of a RadComboBox is null using the following code:

if (String.IsNullOrWhiteSpace(RadComboBox1.SelectedItem.Text))
{
    //Do something
}

However, when the SelectedItem IS null, this code throws a NullReferenceException... the very thing I was trying to check for.

I found this question which describes how to check if a ComboBox is null, but Telerik's RadComboBox does not have a "SelectedText" property.

How can rewrite this simple code to check if the RadComboBox has an item selected or not?

Community
  • 1
  • 1
Sesame
  • 3,370
  • 18
  • 50
  • 75

1 Answers1

2

First check SelectedItem for null and then check its Text property like:

if (RadComboBox1.SelectedItem != null && 
    String.IsNullOrWhiteSpace(RadComboBox1.SelectedItem.Text))

If there is no item selected then SelectedItem would be null and accessing its property Text would cause NRE.

Your current check is not checking for SelectedItem being null, instead it is only checking if the property Text is Null or WhiteSpace.

Habib
  • 219,104
  • 29
  • 407
  • 436