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
- }
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
- }
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