Several time while developing asp .NET applications we need to transfer daa from
1. Using Query String
2. Using Cookies
3. Using Session Variables
4. Using Cross Page Posting
5 . Using Server.Transfer
1 . QueryStrings
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
private void btnGO_Click(object sender, System.EventArgs e)
{
Response.Redirect("Default2.aspx?Value=" +txtData.Text);
}
To retrieve this value on second page
private void Page_Load(object sender, System.EventArgs e)
{
txtData.Text = Request.QueryString["Value"];
}
If we have passed more than one values in querystring we can either retrieve them by variable name or by index
private void Page_Load(object sender,System.EventArgs e)
{
txtData.Text = Request.QueryString[0];
}
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
private void btnGO_Click(object sender, System.EventArgs e)
{
Response.Redirect("Default2.aspx?Value=" +
txtData.Text.Replace(" ","%20");
}
Or we can use Server.UrlEncode methodprivate void btno_Click(object sender, System.EventArgs e)
{
Response.Redirect("Default2.Aspx?" +
"Name=" + Server.UrlEncode(txtData.Text));
}
2. Data Transfer Using Cookies
Cookies are stored in client machine and can have max size of 4kb
To store value from textbox
protected void btnGo_Click(object sender, EventArgs e)
{
HttpCookie MyCookie = new HttpCookie("Data");
MyCookie.Value = txtData.Text;
MyCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(MyCookie);
Response.Redirect("Deault2.aspx");
}
And to retrieve data from cookie in Deault2.aspx pageIn the Page_Load event write
String strData = Request.Cookies["Data"].Value);
3. Data Transfer using Session Variables
Storing and retrieving Data to and from
session variables on the page we want
To store a value in session we need to write
protected void btnGo_Click(object sender, EventArgs e)
{
Session["VariableName"] = txtData.Text;
Response.Redirect("Deault2.aspx");
}
To retrieve value from Session on other page
string strData = Session["VariableName"].ToString();
Don't forget to use proper typecasting as session stores data as Object and we need to change it to desired type.
To remove Session Variables use