Today's Question:  What does your personal desk look like?        GIVE A SHOUT

Check if query string variable exists ASP.NET C#/VB

  Jamie Connolly        2011-11-05 15:29:50       26,027        0    

One of the problems I encountered when I started programming ASP.NET websites was to do with the Request.QueryString function. The first projects I was worked on were built with VB.NET and I used the following code to check the existence of a query string variable:

VB.NET Code

  1. If Request.QueryString("[VARIABLE]") <> Nothing Then  
  2.       'CODE HERE  
  3. End If  

This code checked if the variable existed and if it was populated.

Moving to C# I automatically assumed that the â€˜Nothing’ keyword directly translated into empty quotes ("") as shown below:

C#.NET Code

  1. if (Request.QueryString["[VARIABLE]"] != "") {  
  2.     // CODE HERE  
  3. }  
NOTE: Notice the difference in the bracket types between VB.NET and C#, VB uses rounded brackets () for array selection while C# uses square brackets [] for array selection.

After a while I noticed that if the VARIABLE was NOT in the query string the ‘if’ statement would return true and the code inside would be executed. To counter this problem an additional check must be made which check the existence of the query string variable itself. The following code shows how to check for this:

C#.NET Code

  1. if (Request.QueryString["[VARIABLE]"] != "" && Request.QueryString["[VARIABLE]"] != null) {  
  2.     // CODE HERE  
  3. }  
NOTE: This conditional will only work if both conditions are checked using the AND (&&) logical operator and NOT the OR (||) logical operator.

This section of code will now check for both the existence of the specified variable in the query string including if it contains a value.

I hope this post helps you !

Jamie

Source:http://www.jamieconnolly.net/index.php/blog/asp-dot-net/check-if-query-string-variable-exists-aspnet-cvb/

ASP.NET   QUERY STRING  REQUEST  EMPTY  NULL  CHECK 

Share on Facebook  Share on Twitter  Share on Weibo  Share on Reddit 

  RELATED


  0 COMMENT


No comment for this article.