Checking of empty and null string in asp.net using C#

In this tutorial we will learn how to check the empty string and null string in asp.net using C#. But before moving forward let’s understand what is the difference between null string and empty string.

Null String:-
A string is said to be a Null String if it hasn’t been assigned any value yet.

Empty String:-
A string is said to be an Empty String that has been assigned an empty value.

Empty and null string is different and we must differentiate between them.

You may get error if you want to check the certain property of the string i.e; length of the string then you may get error if that string is NULL because we can’t get the length of Null String. So it’s better to check the string before applying any function over it. In this tutorial we will learn how to detect empty string as well as null string in asp.net using C#.

Now let’s consider we have a textbox in .aspx web page suppose we have
<asp:TextBox ID="txt_Name" runat="server"></asp:TextBox> in our .aspx webpage now on Button’s OnClick event we are going to check whether txt_Name contains empty/Null value or not.

Methods to check the empty string:-

In this section we will learn different techniques to detect the empty string in asp.net using c#

Check_empty_null_string.aspx.cs

Method 1
if (txt_Name.Text.ToString().Equals(""))
{
lbl_message.Text="Contains Empty value";
}

Method 2
if (txt_Name.Text.ToString().Length == 0)
{
lbl_message.Text="Contains Empty value";
}

Method 3
if (txt_Name.Text.ToString().Equals(""))
{
lbl_message.Text="Contains Empty value";
}

Methods to check the null string:-

if (txt_Name.Text.ToString() == null)
{
lbl_message.Text="Contains Null value/ Null string";
}

Sometimes you may get error like this Object reference not set to an instance of an object when you intend to get any property of the string but that string is null, so it’s better to check the empty string as well as null string in one statement to make code as short as you can ant to make application more free.

Methods to check the null string and empty string in one statement

Method1
if (string.IsNullOrEmpty(txt_Name.Text.ToString()))
{
lbl_message.Text="Contains Empty value or Null Value";

}

Method2
if(txt_Name.Text.ToString()!=null && txt_Name.Text.ToString()!=string.Empty)
{
lbl_message.Text="String is neither empty nor null";
}

You can also check the existence of empty string or null string by applying the above mentioned methods over the values coming from database.

So this is the way to check and detect the empty and null string in asp.net using c#.



0 comments: