Tag Archives: NameValueCollection Example

Using ParseQueryString to get QueryString Values

Following is the sample code you can use to parse your querystring and return NameValueCollection

[code]

protected void Page_Load(object sender, EventArgs e)
{
String currurl = HttpContext.Current.Request.RawUrl;
String querystring = null ;

// Check to make sure some query string variables
// exist and if not add some and redirect.
int iqs = currurl.IndexOf(‘?’);
if (iqs == -1)
{
String redirecturl = currurl + "?var1=1&var2=2+2%2f3&var1=3";
Response.Redirect(redirecturl, true);
}
// If query string variables exist, put them in
// a string.
else if (iqs >= 0)
{
querystring = (iqs < currurl.Length – 1) ? currurl.Substring(iqs + 1) : String.Empty;
}

// Parse the query string variables into a NameValueCollection.
NameValueCollection qscoll = HttpUtility.ParseQueryString(querystring);

// Iterate through the collection.
StringBuilder sb = new StringBuilder("");
foreach (String s in qscoll.AllKeys)
{
sb.Append(s + " – " + qscoll[s] + "");
}

// Write the result to a label.
ParseOutput.Text = sb.ToString();

}

[/code]

This is the front end code ,

[code]

<form id="form1" runat="server">
Query string variables are:
<asp:label id="ParseOutput" runat="server">
</asp:label></form>

[/code]

Hope this Helps 🙂