Friday 2 December 2011

Asp.Net QueryString Example

In this post i am explaining how to use querystrings.

Example url with querystring can be something similar like this

http://yahoo.com/defauld.aspx?variable1=value1&variable2=value2

Suppose we have a textbox txtData and we want it's value on other page
than in code behind we would write in click event of btnGo


1private void btnGO_Click(object sender, System.EventArgs e)
2{
3Response.Redirect("Default2.aspx?Value=" +
4txtData.Text);
5}


Or

1private void btnGO_Click(object sender, System.EventArgs e)
2{
3Response.Redirect("Default2.aspx?city=" +
4txtData.Text + "&country=" + txtcountry.Text);
5}


Now to retrieve these values on other page we need to use request.querystring, we can either retrieve them by variable name or by index

1private void Page_Load(object sender,System.EventArgs e)
2{
3txtCity.Text = Request.QueryString["city"];
4txtCountry.Text = Request.QueryString["country"];
5}

Or we can also use

1private void Page_Load(object sender,System.EventArgs e)
2{
3txtCity.Text = Request.QueryString[0];
4txtCountry.Text = Request.QueryString[1];
5}


QueryString can't be used for sending long data because it has a max lenght limit

Data being transferred is visible in url of browser

To use spaces and & in query string we need to replace space by %20 and & by %26

1private void btnGO_Click(object sender, System.EventArgs e)
2{
3Response.Redirect("Default2.aspx?Value=" +
4txtData.Text.Replace(" ","%20");
5}

Or we can use Server.UrlEncode method

1private void btno_Click(object sender, System.EventArgs e)
2{
3Response.Redirect("Default2.Aspx?" +
4"Name=" + Server.UrlEncode(txtData.Text));
5}

No comments:

Post a Comment