null and its related problem
I have recieved many queries stating that my ViewState is null than to (ViewState["Test"] != null) doesn't satisfies, what could be the problem why i am recieving such a abnormal output.
Identifying the cause of problem and its resolution
Case 1: When assigning unassigned value to ViewState or Session.
Example:
int iFlag;
ViewState["Test"] = iFlag;
if (ViewState["Test"] != null)
{
Response.Write("I am In");
}
else
{
Response.Write("I am Out");
}
Thanks to the compiler that it identifies such errors at compile time and so it wouldn't be headache for yours.
//Output of above code.
Error : Use of unassigned local variable 'iFlag'
Case 2: When assigning unassigned value of class variable to ViewState or Session.
Example:
ViewState["Test"] = clsGlobal.iFlag; //Definition in clsGlobal: public static int iFlag;
if (ViewState["Test"] != null)
{
Response.Write("I am In");
}
else
{
Response.Write("I am Out");
}
//Output of above code.
I am In
Note: whenever you are assigning integer value to ViewState or Session, unassigned int value is not equals to null and so the output.
Same code with unassigned string variable of class would have work perfectly as per your desire as unassigned string variable is null.
Example:
ViewState["Test"] = clsGlobal.striFlag; //Definition in clsGlobal: public static string striFlag;
if (ViewState["Test"] != null)
{
Response.Write("I am In");
}
else
{
Response.Write("I am Out");
}
//Output of above code.
I am Out
So the moral of disscusion is to avoid such errors it is better to take precaution before assigning integer value to ViewState or Session.
Example:
if(clsGlobal.iFlag != 0)
ViewState["Test"] = clsGlobal.iFlag;
if (ViewState["Test"] != null)
{
Response.Write("I am In");
}
else
{
Response.Write("I am Out");
}
This code will work perfectly
//Output of above code.
I am Out