GVA Grimly Image 1
Edinburgh Libraries 1
GVA Grimly Image 2
Edinburgh Libraries 2
Buchanan Galleries 1
27th
2009

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

Posted by Jamie Connolly

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

If Request.QueryString("[VARIABLE]") <> Nothing Then
      'CODE HERE
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

if (Request.QueryString["[VARIABLE]"] != "") {
	// CODE HERE
}
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

if (Request.QueryString["[VARIABLE]"] != "" && Request.QueryString["[VARIABLE]"] != null) {
	// CODE HERE
}
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


3 Comments in “Check if query string variable exists ASP.NET C#/VB”

Hi,
Ugh, I liked! So clear and positively.
Rufor

Great info. Thank you very much for the insight.

Or try:

if (!String.IsNullOrEmpty(Request.QueryString["[VARIABLE]"]))

Does the same thing


Leave a Reply

Search website

Search

Blog Categories

Designers

 

« back to blog home