Benji
Benji

Reputation: 635

Set up an if else statement to check for query string

I'm trying to set up a page that checks for two different query string using an if else statement. It works great as long as I only use one of the if statements and if I put both of them, the one I put on top works while the other one gives me an error. This is the code I've used:

if (Request.QueryString.HasKeys())
{
    if (!Page.IsPostBack)
    {
        if (Request.QueryString["foo"].Equals("Success"))
            lblUpdate.Text = "Message 1";
        else if (Request.QueryString["bar"].Equals("Success"))
            lblUpdate.Text = "Message 2";
        else
            lblUpdate.Text = "";
    }
}

I have tried a few other things but I always run into the same problem, that the 2nd statement doesn't work.

Upvotes: 0

Views: 1907

Answers (1)

Habib
Habib

Reputation: 223187

You should check for null first and then compare the value like:

if (Request.QueryString["foo"] != null 
     && Request.QueryString["foo"].Equals("Success"))
    lblUpdate.Text = "Message 1";
else if (Request.QueryString["bar"] != null 
    && Request.QueryString["bar"].Equals("Success"))
    lblUpdate.Text = "Message 2";
else
    lblUpdate.Text = "";

Since it appears that only one of the query string would be present so you will end up with Null reference exception.

You can also check for contains like:

Request.QueryString.AllKeys.Contains("foo")

Upvotes: 6

Related Questions