Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Checking for null....... 1

Status
Not open for further replies.

TiltingCode

Programmer
Apr 10, 2009
61
US

I've tried two ways to check for null and neither work:
I have a menu control and when I click a link the below event is fired. I tried two ways to check for null and neither work. Can someone please help?

protected void MenuItems_OnMenuItemClick(object sender, MenuEventArgs e)
{
try
{
if ( e.Item.Text != null)
{
Debug.WriteLine("MenuItem: " + e.Item.Text );
}
}
catch(Exception ex)
{
throw (ex);
}
}

And:

protected void MenuItems_OnMenuItemClick(object sender, MenuEventArgs e)
{
try
{
System.Web.UI.WebControls.MenuItem mi = new System.Web.UI.WebControls.MenuItem();

if (mi.Parent.Text != null)
{
Debug.WriteLine("MenuItem: " + e.Item.Text );
}
}
catch(Exception ex)
{
throw (ex);
}
}
 
Have you tried with the built in string.isNullOrEmpty?

if (!string.IsNullOrEmpty(mi.Parent.Text))
{
code
}
 
Yes, I just tried that and then I tried if(!string.IsNullOrEmpty(mi.Parent.Text.ToString())) and if (!string.IsNullOrEmpty(e.Item.Parent.Parent.Text)) which didn't work either. I appreciate your attempt, Moregelen. Do you or anyone else have any other ideas?
 
If that is saying it isn't null, then it most likely isn't null. Have you run it in debugging mode to verify that it really is a NULL?
 
Here is what I get using debug and then in the exception:

?e.Item.Parent.Parent.Text
'e.Item.Parent' is null
Step into: Stepping over non-user code 'System.Web.UI.WebControls.MenuEventArgs.Item.get'
A first chance exception of type 'System.NullReferenceException' occurred in App_Web_fjsl66dx.dll
A first chance exception of type 'System.NullReferenceException' occurred in App_Web_fjsl66dx.dll
 
Oh. Your issue isn't that the text isn't null, its that the parent is null.

Try with:

if (e.Item.Parent != null && !string.IsNullOrEmpty(e.Item.Parent.Text))
{
code
}
 
Or whatever it is. Make sure the top level elements aren't null.
 
That did it! Thanks so much. I've been struggling with null values in C# all day. Part of the learning process.... Thanks again!.
 
Yup. Just remember that if its possible for an object higher up to be null, you need to check that first. Doing e.Item.Parent.Text is going ahead and making the assumption that Parent isn't null; so when it is null, things crash and burn.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top