Query String allows you to pass values between the asp.net pages.
Let us say, you are navigating to below URL
![QueryString1.gif]()
In above URL, you are navigating to a page called Add.aspx and Number1 and
Number2 are query string to page Add.aspx.
To create Query String,
- Add a question mark (?) to URL.
- After Question mark, give variable name and value separated by equal to (=).
- If more than one parameter need to be passed then separate them by ampersand
(&).
To read query String,
Say your URL is,
http://localhost:12165/Add.aspx?Number1=72&Number2=27
Then to read query string, on Add.aspx
![QueryString2.gif]()
You can read by passing exact variable name in index or,
![QueryString3.gif]()
You can read, by passing index value as above.
Now, I am going to show you a very basic sample, - I will create a page with two text boxes and one link button.
- I will pass text boxes values as query string to other page on click event of
link button.
- On the other page, I will read the query string value and will add them in
display in a label.
I have created a new asp.net application. Then I dragged and dropped two
textboxes and one link button on the page. On click event of link button, I am
performing the below operation.
![QueryString4.gif]()
I am constructing the URL, as to navigate to Add.aspx page and then appending
two query strings from textbox1 text and textbox2 text.
Now, add a page to project say Add.aspx . Drag and drop a label on the page. On
the page load event perform the below operation.
![QueryString5.gif]()
So, when you run the application you will get the output as below,
![QueryString6.gif]()
For your reference, the whole source code is given below,
Default.aspx.cs
using
System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Web;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
namespacequeryparameterexample
{
publicpartialclass_Default
: System.Web.UI.Page
{
protectedvoidPage_Load(object
sender, EventArgs e)
{
}
protectedvoid
LinkButton1_Click(object sender,
EventArgs e)
{
stringurltoNaviget
= "~/Add.aspx?Number1=" +
TextBox1.Text +
"&Number2=" +
TextBox2.Text;
LinkButton1.PostBackUrl = urltoNaviget;
}
}
}
Add.aspx.cs
using
System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Web;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
namespacequeryparameterexample
{
publicpartialclassWebForm1
: System.Web.UI.Page
{
protectedvoidPage_Load(object
sender, EventArgs e)
{
string
number1 = Request.QueryString[0];
string number2 =
Request.QueryString[1];
// The other way
to Read the values
//string number1 = Request.QueryString["Number1"];
//string number2 = Request.QueryString["Number2"];
int
result = Convert.ToInt32(number1) +
Convert.ToInt32(number2);
Label2.Text = result.ToString();
}
}
}
I hope this post is useful. Thanks for reading. Happy Coding.