Friday, April 9, 2010

QueryString - Passing variable Between Pages ASP.Net

QueryString is user for passing variable in between pages. for example you need to pass ones first name and last name from one page to another page, you can use QueryString. you can collect first name from page one and send that information via query string.

Example of a QueryString is search.aspx?fname=john&lname=thomas

 "?" starts the QueryString and "&" is used to add more variables
Advantages of QueryString is its very easy to use but it have limitations you cant sent large information via QueryString, QueryString have max length. you cant send [&] and [space]  via QueryString. do not send secure information like username and password via QueryString.

Example for Send QueryString

// taking First Name and Last Name in two Variables
string firstName=txtFirstName.Text;
string lastName=txtLastName.Text;

// format QueryString using string format
string qStringVaribales = string.Format("fname={0}&lname={1}", firstName, lastName);

// alternate method
string qStringVaribales="?fname="+firstName+"&lname="+lastName;

// Redirect QueryString to second page
Response.Redirect("search.aspx" + qStringVaribales);

Receive QueryString 

// Checking QstringString is null or empty
 // assigning QueryString in Variables

        if (Request.QueryString["fname"] != null && Request.QueryString["fname"] != "")
            string firstName = Request.QueryString["fname"];
        if (Request.QueryString["lname"] != null && Request.QueryString["lname"] != "")
            string lastName = Request.QueryString["lname"];

No comments: