views:

21

answers:

3

Hi,

Hi , I have a varible sem,which takes inputfrom the textbox but if the textbox is kept empty i want it to return "Please Enter a Semester"

    int sem;
    int parsevalue;
    if (int.TryParse(TextBox2.Text, out parsevalue))
    {
        sem = parsevalue;
        Session["Sem"] = sem;
    }
    else
    {
        Literal2.Text = "Please Enter a Semester";
    }

But If the Textbox is empty the Session["Sem"] returns NullExceptionError in the .aspx file where i have used it.

I searched for the proper conversion using tryparse but could not understand it clearly as to how to print the above mentioned error message. please help Thank you in advance

A: 

Try:

 HttpContext.Current.Session["Sem"] = sem;

Actually:

 Session.Add("Sem", sem);

and

 Session["Sem"] = sem;

is a same

Michael Pakhantsov
Actually, it's all the same, so it won't solve his problem. :-)
Prutswonder
A: 

The problem here is that you're assigning the Session variable only when there is a correct value, but you're always trying to access it. This will fail if the value is incorrect (and the Session variable is not set).

Here's your corrected code:

int sem;
int parsevalue;
if (int.TryParse(TextBox2.Text, out parsevalue))
{
    sem = parsevalue;
}
else
{
    Literal2.Text = "Please Enter a Semester";
}
//Always set the Session variable when it's used somewhere else
Session["Sem"] = sem;
Prutswonder
A: 

Q1 Hi , I have a varible sem,which takes inputfrom the textbox but if the textbox is kept empty i want it to return "Please Enter a Semester"

    int sem;
    int parsevalue;

    var txt = TextBox2.Text

    if (!String.IsNullOrEmpty(text) && int.TryParse(text, out parsevalue))
    {
        sem = parsevalue;            
    }
    else
    {
        Literal2.Text = "Please Enter a Semester";
    }

    Session["Sem"] = sem;
Vash