C#中的五种界面间传值方法

C#中五种界面间传值方法:

 一、Session传值(保存在服务端)


login.aspx.cs页面中:
        新建一个login.aspx页面,添加用户名和密码,以及两个文本框,和一个Button安扭,在button按钮的单击事件中,填写如下代码:
	Session["name"] = TextBox1.Text.Trim();
	Session["password"] = TextBox2.Text.Trim();
	Response.Redirect("index.aspx");

index.aspx.cs页面中

   新建一个index.aspx页面,在Page_load()方法中写入如下代码:
	 Response.Write("
你的用户名是:"+Session["name"].ToString()); Response.Write("
你的密码是:" + Session["password"].ToString());

用完后消除Session的值,以免浪费系统资源 :Session.Remove("name"); Session.Remove("password");

            

二、通过URL传值(这种传值方法不安全,信息会显示在地址栏)


     login.aspx.cs页面中
	string name = TextBox1.Text.Trim();
     	string password = TextBox2.Text.Trim();
	Response.Redirect("index.aspx?name="+name+"&password="+password);

 
       
   
  index.aspx.cs页面中 
  
     	Response.Write("
你的用户名是:"+Request.QueryString["name"]); Response.Write("
你的密码是:"+Request.QueryString["password"
]);

三、Cookie传值(保存在客户端)


         login.aspx.cs页面中
        string name = TextBox1.Text.Trim();
        string password = TextBox2.Text.Trim();
        //实例化cookie类
        HttpCookie cookie_name = new HttpCookie("name");
        HttpCookie cookie_password = new HttpCookie("password");
        cookie_name.Value = name ;
        cookie_password.Value = password;
        Response.AppendCookie(cookie_name );
        Response.AppendCookie(cookie_password);
        Server.Transfer("index.aspx");//跳转到页面index.aspx
          index.aspx.cs页面中
	Response.Write("
你的用户名是:" +Request.Cookies["name"].Value.ToString()); Response.Write("
你的密码是:" + Request.Cookies["password"].Value.ToString());
    注意:执行后浏览器的临时文件夹中会生成一个txt的文本文件,该文件包含cookie所传的值。

四、使用Application 对象变量

  a.aspx的C#代码
	private void Button1_Click(object sender, System.EventArgs e)
        {
		Application["name"] = Label1.Text;
		Server.Transfer("b.aspx");
        }
b.aspx中C#代码
	private void Page_Load(object sender, EventArgs e)
        {
		string name;
		Application.Lock();
		name = Application["name"].ToString();
		Application.UnLock();
        } 

五、使用Server.Transfer方法
   
a.aspx的C#代码
	public string Name
        {
		get{ return Label1.Text;}
        }
	private void Button1_Click(object sender, System.EventArgs e)
        {
		Server.Transfer("b.aspx");
        }

b.aspx中C#代码

	private void Page_Load(object sender, EventArgs e)
        {
		a newWeb;//实例a窗体
		newWeb = (source)Context.Handler;
		string name;
		name = newWeb.Name;
        }


你可能感兴趣的:(C#)