Click here to Skip to main content
Click here to Skip to main content

Passing variables between pages using QueryString

By , 18 Jan 2004
 

Introduction

Often you need to pass variable content between your html pages or aspx webforms in context of Asp.Net. For example in first page you collect information about your client, her name and last name and use this information in your second page.

For passing variables content between pages ASP.NET gives us several choices. One choice is using QueryString property of Request Object. When surfing internet you should have seen weird internet address such as one below.

http://www.localhost.com/Webform2.aspx?name=Atilla&lastName=Ozgur

This html addresses use QueryString property to pass values between pages. In this address you send 3 information.

  1. Webform2.aspx this is the page your browser will go.
  2. name=Atilla you send a name variable which is set to Atilla
  3. lastName=Ozgur you send a lastName variable which is set to Ozgur

As you have guessed ? starts your QueryString, and & is used between variables. Building such a query string in Asp.Net is very easy. Our first form will have 2 textboxes and one submit button.

Put this code to your submit button event handler.

private void btnSubmit_Click(object sender, System.EventArgs e)
{
Response.Redirect("Webform2.aspx?Name=" +
this.txtName.Text + "&LastName=" +
this.txtLastName.Text);
} 

Our first code part builds a query string for your application and send contents of your textboxes to second page. Now how to retrieve this values from second page. Put this code to second page page_load.

private void Page_Load(object sender, System.EventArgs e)
{
this.txtBox1.Text = Request.QueryString["Name"];
this.txtBox2.Text = Request.QueryString["LastName"];
} 

Request.QueryString is overloaded with a second way. You can also retrieve this values using their position in the querystring. There is a little trick here. If your QueryString is not properly built Asp.Net will give error.

private void Page_Load(object sender, 

System.EventArgs e)
{
this.txtBox1.Text = Request.QueryString[0];
this.txtBox2.Text = Request.QueryString[1];
}

Some other ways to reach contents of QueryString.

foreach( string s in Request.QueryString)
{
Response.Write(Request.QueryString[s]);
}

Or 

for (int i =0;i < Request.QueryString.Count;i++)
{
Response.Write(Request.QueryString[i]);
} 

Advantages of this approach

  1. It is very easy.

Disadvantages of this approach

  1. QueryString have a max length, If you have to send a lot information this approach does not work.
  2. QueryString is visible in your address part of your browser so you should not use it with sensitive information.
  3. QueryString can not be used to send & and space characters.

If you write this code and try them you will see that you have a problems with space and & characters, e.g. if you need to send a variable which contains & such as "Mark & Spencer". There must be a solution for this problem. If you look to Google’s query string you will see that it contains a lot of %20. This is the solution of our third disadvantage. Replace space with %20 and & with %26 for example.

private void btnSubmit_Click(object sender, System.EventArgs e)
{
string p1 = this.txtName.Text.Replace("&","%26");
p1 = this.txtName.Text.Replace(" ","%20");
string p2 = this.txtLastName.Text.Replace("&","%26");
p2 = this.txtName.Text.Replace(" ","%20"); 
            "WebForm2.aspx?" + 
            "Name=" + p1 + 
            "&LastName=" + p2;
Response.Redirect(p2);
} 

Since this is a such a common problem Asp.Net should have some way to solve. There it is Server.UrlEncode. Server.UrlEncode method changes your query strings to so that they will not create problems.

 private void btnSubmit_Click(object sender, System.EventArgs e)
{
Response.Redirect("WebForm2.Aspx?" + 
"Name=" +   Server.UrlEncode(this.txtName.Text) + 
"&LastName=" + Server.UrlEncode(this.txtLastName.Text)); 
} 

Same solution is in Microsoft .Net Quick Start tutorials.

ASP.NET --- Working with Web Controls ---

--- Performing Page Navigation (Scenario 1) ---
--- Performing Page Navigation (Scenario 2) ---

Look at them also if you want to see more example for this technique. Also I advise you to look at Alex Beynenson's article about building QueryString(s).

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Atilla Ozgur
ISKUR
Turkey Turkey
Member
I started programming in 1991 with Amiga 68000 Assembler. I am a web and database developer proficient in different languages and databases

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5membercs10100023 Dec '12 - 9:24 
Very simple, very usefull. Thanks!
GeneralMy vote of 5memberJrPacheco8 Nov '12 - 2:03 
Very Nice! Resolved my problem!
GeneralMy vote of 4membervijayasai Goparaju25 Oct '12 - 1:01 
useful and understandable
GeneralMy vote of 2memberNigam Patel8 Oct '12 - 3:54 
don't use this keyword people are confuse and they understand this is the keyword need to use for the query string.
QuestionRedirecting page particular passing parameter?memberMember 917112818 Sep '12 - 22:51 
Your blog is very help full,
I have one requirement like this
I have a table CUSTOMER in that CUSTID,NAME,URL columns is thier
CUSTID NAME URL
1 asp www.asp.net
2 weblog www.weblogs.asp.net
3 google www.google.com
 
My question is I opening perticular url based on CUSTID
 
I am Passing parameter Like www.Example.com?CUSTID=1 That
 
corressponding URL data(Ex:www.asp.net) It will open directly in browser
 
using asp.net........
plz help me ...........
Thank you,
anil
AnswerRe: Redirecting page particular passing parameter?memberMember 917112826 Sep '12 - 15:22 
plz any body help me.........
Questionmy vote of fivememberalejandro29A17 Sep '12 - 1:36 
excellent! clean and right to the subject!, thanks! Big Grin | :-D
Dios existe pero duerme...
Sus pesadillas son nuestra existencia.
(Ernesto Sabato)

Generalnicemembersource.compiler11 Aug '12 - 15:49 
thats realy complete for beginners
GeneralMy vote of 5memberlmcatony10 Aug '12 - 7:45 
Thanks very much, good article!
Questionhfjmembergajendra2256 Jul '12 - 21:01 
hhjj
Questionquery stringmemberRamya.Raju.M15 Jun '12 - 22:17 
Easily explained...thanks Smile | :) Thumbs Up | :thumbsup:
QuestionQuery StringmemberSharda Vishwakarma18 May '12 - 21:12 
Very much usefull article
AnswerRe: Query Stringmemberraikripa22 Jun '12 - 2:18 
Poke tongue | ;-P D'Oh! | :doh: Java | [Coffee]
Suggestioneasy concept of query stringmemberatulkath284 Apr '12 - 2:12 
follow this article to make query string easier for you
 

http://fresherpoint.com/articles/index.php/how-to-pass-the-parameter-in-query-string-with-examplesolved/[^]
GeneralMy vote of 5memberSam Path21 Feb '12 - 18:19 
Simple for understand ..
GeneralMy vote of 3memberKailash_Singh3 Nov '11 - 23:56 
...Smile | :)
QuestionXML to connect to URL?membertomngs9 Sep '11 - 4:25 
How do I parse this?
 http://mywesite.com/xml.aspx?data=<clickAPI><sendMsg><api_id>1</api_id>
s<user>demo</user><password>demo</password><to>448311234567</to><text>Meet me outside</text><from>me</from></sendMsg></clickAPI>

QuestionQuery string - nice articlememberFergal19707 Sep '11 - 9:56 
Nice article. Simple, clear and concise for an ASP beginner like me!
GeneralMy vote of 5memberlopinti5 Jul '11 - 21:14 
i really liked this article, beginers like me , can understand very well, thank you
GeneralMy vote of 4memberrmksiva29 May '11 - 23:45 
very nice and easy to understand...
GeneralMy vote of 5memberlangkow15 Apr '11 - 3:31 
very well written
GeneralMy vote of 4memberMember 39118731 Feb '11 - 23:44 
Explained properly
QuestionHow to display data in a gridview by make use of querystringmemberBoney19844 Jan '11 - 16:01 
Hi friends,
I am doing a project in asp.net C# with sqlserver as database
I have 2 pages customercorner.aspx & processingreq.aspx
In customercorner.aspx I have used following code
string work_field=ListBox1.SelectedItem.Text;

Response.Redirect("ProcessingReq.aspx?work_field");

At the receiving end
protected void Page_Load(object sender, EventArgs e)
{
string field_work = Request.QueryString["work_field"];
}
I need to use a gridview by accepting field_work as a parameter
How can we do?
GeneralMy vote of 5memberroshan1234567822 Sep '10 - 20:04 
there have many program it is easy to use and learn so many things
GeneralMy vote of 5memberSharad Kulkarni22 Sep '10 - 0:36 
clear and clean information. Directly implementable!
GeneralMy vote of 1membersayhello.siddu5 Aug '10 - 22:43 
the author is not aware of the inbuilt html helpers
GeneralQuery StringsmemberDursetty Kaveri22 Jun '10 - 22:34 
Hi

As a New User to Query Strings..........
 
I have taken 2 TextBoxes (for name & pwd) 1 ButtonControl object (for login) and 4 Hyper LinkControls as Home, OurServices, EmployeeLogin, ContactUs.In EmployeeLogin again i have 2 TextBoxes & 1 ButtonControl.

My Problem Specification is if the user enteres his name & pwd then he can enter into all the links specified except EmployeeLogin.If the Administrator enter his name & pwd he can enter into all the .aspx pages
 
How to sort out this problem using query strings....
 
Please Some One Help me to sort out this.
 
Thank you......
GeneralMy vote of 1member_Armen1 Oct '09 - 4:30 
poor
GeneralExecelent Articlememberasif hossain shantu29 Sep '09 - 19:12 
Hi , you have created a great article, best of luck
 
Regards
Shantu

GeneralQuery String Passmemberprabusundaram23 Jan '09 - 1:18 
I get clicked row of data from gridview to another page using query string. but when i change the value to new page. only old values are being not new value taken. also get error when update its showing data type mismatching.
Help anyone
GeneralQueryString helpmemberdomenicfz9 Dec '08 - 9:07 
I have a jpeg of the map of US, I have created hotspots on all 50 states. I would like the user to click on whatever state they want and i want it then to pull up a page with that states name on it. Click on Ohio then the next page has the word OHIO printed on it.
 
I am very confused at this point on how to make that happen and was hoping someone could help me out here. Right now I am looking at creating 50 seperate pages instead of just 1 page.
GeneralHELP!?!memberPhilly Burton8 Oct '07 - 4:38 
I'm trying to pass a query string, it seems really simple but I cant do it.
 
All Im trying to do is take a stock number from a list of results in a datalist and put it in the query string.
 
Here's my aspx page code and my c# code
 
--------------------------------- Default.aspx
<%@ Page Language="C#" AutoEventWireup="true"   CodeFile="Default.aspx.cs" Inherits="_Default" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
      <title>Untitled Page</title>
</head>
<body>
      <form id="form1" runat="server">
      <div>
            &nbsp;<asp:DataList ID="DataList1" runat="server" DataSourceID="AccessDataSource1">
                  <ItemTemplate>
                        Make:
                        <asp:Label ID="MakeLabel" runat="server" Text='<%# Eval("Make") %>'></asp:Label><br />
                        Model:
                        <asp:Label ID="ModelLabel" runat="server" Text='<%# Eval("Model") %>'></asp:Label><br />
                        <asp:TextBox ID="StockNumberLabel" runat="server" Text='<%# Bind("StockNumber") %>'
                              Visible="True"></asp:TextBox><br />
                        <br />
                        <asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click1">LinkButton</asp:LinkButton>
                  </ItemTemplate>
            </asp:DataList><asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="~/App_Data/TEST.MDB"
                  SelectCommand="SELECT [Make], [Model], [StockNumber] FROM [test]"></asp:AccessDataSource>
     
      </div>
      </form>
</body>
</html>
------------------------------------------
 
and heres my c# code
 
------------------------------------------default.aspx.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
 
public partial class _Default : System.Web.UI.Page
{
      protected new System.Web.UI.WebControls.TextBox StockNumberLabel;
 
      protected void Page_Load(object sender, EventArgs e)
      {
 
      }
      protected void LinkButton1_Click1(object sender, EventArgs e)
      {
            string p1 = this.StockNumberLabel.Text;
            string sln = "Default2.aspx?" + p1;
 
            Response.Redirect(sln);
      }
 
  
}
----------------------------------------------
 
It keeps returning this error:
 
System.NullReferenceException was unhandled by user code
   Message="Object reference not set to an instance of an object."
   Source="App_Web_dhy1xh03"
   StackTrace:
         at _Default.LinkButton1_Click1(Object sender, EventArgs e) in c:\Users\Philly B\Documents\Visual Studio 2005\WebSites\WebSite2\Default.aspx.cs:line 22
         at System.Web.UI.WebControls.LinkButton.OnClick(EventArgs e)
         at System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument)
         at System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
         at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
         at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
         at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
 

Thanks in advance, Phil
GeneralRe: HELP!?!memberpakiyo27 Nov '07 - 16:56 
Hello, i am prakash my id is abhi-prakash@hotmail.com
 
u wrote this syntax it is a wrong
string sln = "Default2.aspx?" + p1";
 
replace this syntax
string sln="default2.aspx?id={0}" + p1";
 
id--> any name
{0} --> format
GeneralRe: HELP!?!memberdotnetwizmanohar14 May '12 - 22:39 
Hello Phil,
 
you got to write the second page code in under Page_Load(object sender, EventArgs e)
 
after writing it will look like this.
 
protected void Page_Load(object sender, EventArgs e)
{
string p1 = this.StockNumberLabel.Text;
            string sln = "Default2.aspx?" + p1;
 
            Response.Redirect(sln);
 
}
 
Happy Coding!
Cheers!
Generalpassing checkboxlist from page to pagemembersamflex14 Jul '07 - 16:21 
Greetings all,
 
This is indeed a nice forum and I can benefit from your expertise.
 
I am trying to pass 6 values from page1.aspx to page2.aspx.
 
Almost everything seems to be working except CheckBoxList values
 
Assume that the checkboxlist is called txtService. How can I pass this value to page2.asp using querystring?
 
I am using vb.net version 2.o with vs 2003.
 
Thanks in advance.
QuestionHow to retrieve passing filename ?memberHelgeduelbeck29 Jun '07 - 12:29 
Hi,
 
I use masterpage code behind to retrieve variables between pages.
And I have problem to retrieve the last filename that variables comming from.
If 'querystring' is used for variables,
with what reserved words I could retrieve the filename ?
 
Confused | :confused:
GeneralPassing from htmlmemberUnsichtbar22 May '07 - 6:05 
I'm trying to pass a variable as part of a swf insert in html.   Is it possible to pass a variable within the html.   If not, how could it be done?
 

Here is where the swf is inserted.
I want to pass a variable to the sample_xml.aspx file which then genereates xml dynamically.
 

<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
     codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0"
     WIDTH="400"
     HEIGHT="250"
     id="charts"
     ALIGN="">
<PARAM NAME=movie VALUE="charts.swf?library_path=charts_library&xml_source=sample_xml.aspx">
<PARAM NAME=quality VALUE=high>
<PARAM NAME=bgcolor VALUE=#666666>
 
<EMBED src="charts.swf?library_path=charts_library&xml_source=sample_xml.aspx"
         quality=high
         bgcolor=#666666  
         WIDTH="400"
         HEIGHT="250"
         NAME="charts"
         ALIGN=""
         swLiveConnect="true"
         TYPE="application/x-shockwave-flash"
         PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer">
</EMBED>
</OBJECT>
QuestionPass through html link variables to results asp pagememberjohnrobinm20 Mar '07 - 17:55 
hi, is there additional path url code that will trigger the submit button automatically on an asp form page without the user having to click the submit button?
 

GeneralRequest.QueryString is Empty while it show in the URLmemberKarim Rabbani14 Mar '07 - 5:10 
Hai,
I'm using the code in Image Button Event.
response.redirect("admin.aspx?msg=record saved");
 
in admin.aspx url the msg is shown but
request.querystring[msg] is empty
 
help me out
GeneralRe: Request.QueryString is Empty while it show in the URLmemberSubodh Ramugade21 Dec '11 - 20:17 
Not sure if you tried request.querystring["msg"]
Generalplz send me usage of querystringmemberkale.priya9 Jan '07 - 22:24 
plz send me usage of querystring
 
piyu

GeneralRe: plz send me usage of querystringmemberpakiyo27 Nov '07 - 16:58 
Hello priya,
 
i am prakash my id is abhi-prakash@hotmail.com
 
plz give me ur id i am send zip file for this question
 
with database u check it
GeneralHimemberAstalaVista Baby18 Dec '06 - 21:44 
Hellow
 
Devs
GeneralQuery StringmemberPushpa Setty26 Oct '06 - 19:26 
hi i want to add form to change the password.
i think to use query string
 
as i'm new to asp.net plzzz reply me.
how to add the code wen the user clicks the button.
GeneralAbout QueryStringmemberavding8 Jun '06 - 22:15 
As menstioned above that QueryString is expensive when large data,then at this time what we can use, as SessionState is also expensive, any new IDEA?
 
Regards,
avinash
QuestionQuery StringmemberJames Robertson31 Mar '06 - 9:35 
My code below wanting to add the query string to replace the MYUSERNAME@USER.COM with one that is passed from the other web site. What do I need to change and how?
 
Private Sub SendMail(ByVal from As String, ByVal body As String)
Dim mailServerName As String = "MYMAILSERVER"
Dim message As MailMessage = New MailMessage(from, "MYUSERNAME@USER.COM", "Sent From E-Form", body)
Dim mailClient As SmtpClient = New SmtpClient
mailClient.Host = mailServerName
mailclient.Send(message)
message.Dispose()
End Sub
GeneralRequest Querystring in asp.netmembervkancherlapalli@linkageinc.com14 Jul '05 - 6:53 
Hi,
 
I have define
"Public instance_id As Integer = Request.QueryString("i_id")"
above the sub Page_Load - since I want to re-use this variable for all the subs in this aspx page.
 
It comes back with this error message
"Exception Details: System.Web.HttpException: Request is not available in this context"
 
Am I missing something?
 
thanks
GeneralRe: Request Querystring in asp.netmemberSteve Maier14 Jul '05 - 7:14 
Normally you can initialize a variable outside of a function, but what you are trying to do is to call the Request.QueryString. This does not exist yet where you are calling it. It would have to be in one of your functions... like in the pages init function or the page_load.
 
Steve Maier, MCSD MCAD

GeneralRe: Request Querystring in asp.netmembervkancherlapalli@linkageinc.com14 Jul '05 - 7:17 
Thanks!
 
Is there a work around this, I want to initialize this variable only once since it is being used about 5-6 subs and I have to write code in all of them.
 
Or another option to use Session variable, which I don't want to use at this point.
GeneralRe: Request Querystring in asp.netmemberSteve Maier14 Jul '05 - 7:46 
You could intialize the variable in your page_load or the init sub for the page. Those should be called before your other subs unless you call them from the constructor.
 
Steve Maier, MCSD MCAD

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 19 Jan 2004
Article Copyright 2004 by Atilla Ozgur
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid