Click here to Skip to main content
Licence CPOL
First Posted 18 Jan 2004
Views 940,984
Bookmarked 76 times

Passing variables between pages using QueryString

By | 18 Jan 2004 | Article
Pass variables between pages using QueryString and Format with Server.UrlEncode method.

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

Other
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. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionQuery String PinmemberSharda Vishwakarma21:12 18 May '12  
Suggestioneasy concept of query string Pinmemberatulkath282:12 4 Apr '12  
GeneralMy vote of 5 PinmemberSam Path18:19 21 Feb '12  
GeneralMy vote of 3 PinmemberKailash_Singh23:56 3 Nov '11  
QuestionXML to connect to URL? Pinmembertomngs4:25 9 Sep '11  
QuestionQuery string - nice article PinmemberFergal19709:56 7 Sep '11  
GeneralMy vote of 5 Pinmemberlopinti21:14 5 Jul '11  
GeneralMy vote of 4 Pinmemberrmksiva23:45 29 May '11  
GeneralMy vote of 5 Pinmemberlangkow3:31 15 Apr '11  
GeneralMy vote of 4 PinmemberMember 391187323:44 1 Feb '11  
QuestionHow to display data in a gridview by make use of querystring PinmemberBoney198416:01 4 Jan '11  
GeneralMy vote of 5 Pinmemberroshan1234567820:04 22 Sep '10  
GeneralMy vote of 5 PinmemberSharad Kulkarni0:36 22 Sep '10  
GeneralMy vote of 1 Pinmembersayhello.siddu22:43 5 Aug '10  
GeneralQuery Strings PinmemberDursetty Kaveri22:34 22 Jun '10  
GeneralMy vote of 1 Pinmember_Armen4:30 1 Oct '09  
GeneralExecelent Article Pinmemberasif hossain shantu19:12 29 Sep '09  
GeneralQuery String Pass Pinmemberprabusundaram1:18 23 Jan '09  
GeneralQueryString help Pinmemberdomenicfz9:07 9 Dec '08  
GeneralHELP!?! PinmemberPhilly Burton4:38 8 Oct '07  
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!?! Pinmemberpakiyo16:56 27 Nov '07  
GeneralRe: HELP!?! Pinmemberdotnetwizmanohar22:39 14 May '12  
Generalpassing checkboxlist from page to page Pinmembersamflex16:21 14 Jul '07  
QuestionHow to retrieve passing filename ? PinmemberHelgeduelbeck12:29 29 Jun '07  
GeneralPassing from html PinmemberUnsichtbar6:05 22 May '07  

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

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