在兩個頁面之間傳遞信息

在asp.net不同頁面之間傳值的方法主要有三種:
(1)用querystring
方法:在vs2005中新建asp.net網站(發送端),在頁面上添加button,兩個TextBox,代碼如下:
    protected void Button1_Click(object sender, EventArgs e)
    
{
        
string url;
        url 
= "http://localhost/look1/Default.aspx?name=" + TextBox1.Text + "&email=" + TextBox2.Text;
        Response.Redirect(url);
     }
再建接收端頁面,在頁面上添加兩個TextBox,代碼如下:
        TextBox1.Text = Request.QueryString["name"];
        TextBox2.Text 
= Request.QueryString["email"];

(2)使用session變量
private void Button1_Click
(
object sender, System.EventArgs e)
{
Session[
"name"]=TextBox1.Text;
Session[
"email"]=TextBox2.Text;
Server.Transfer(
"http://localhost/look1/Default.aspx");
}

目標頁面代碼:
private void Page_Load
(
object sender, System.EventArgs e)
{
TextBox1.Text
=Session["name"].ToString();
TextBox2.Text
=Session["email"].ToString();
Session.Remove(
"name");
Session.Remove(
"email");
}


(3)使用server.transfer
源頁面代碼:
把以下的代碼添加到頁面中
public string Name
{
get
{
return TextBox1.Text;
}

}


public string EMail
{
get
{
return TextBox2.Text;
}

}

然後調用Server.Transfer方法
private void Button1_Click
(
object sender, System.EventArgs e)
{
Server.Transfer(
"anotherwebform.aspx");
}

目標頁面代碼:
private void Page_Load
(
object sender, System.EventArgs e)
{
WebForm1 wf1;
wf1
=(WebForm1)Context.Handler;
TextBox1.Text
=wf1.Name;
TextBox2.Text
=wf1.EMail;
}


當然,在同一個解決方案裏的不同頁面之間傳值就更簡單了,只需將url改爲頁面名(如:Default2.aspx)就OK了!試試看
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章