Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
570 views
in Technique[技术] by (71.8m points)

c# - How do I access a variable from the code behind of another page?

I have an index.aspx (index.aspx.cs) which will include the body.aspx (body.aspx.cs) using Server.execute("body.aspx");

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;

public partial class index : System.Web.UI.Page
{
    public string text1 = "abc";

    protected void Page_Load(object sender, EventArgs e)
    {
        

    }

}

In index.aspx.cs, there is a variable text1 which I want to use in body.aspx.cs, how to do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think you're thinking of ASP.NET the wrong way. I guess you started as a Windows Developer.

ASP.NET Forms are not like Windows Forms.

You have to understand that the ASP.NET page only lives until the request is being served. And then it "dies".

You cannot pass variables from/to pages the same way you do with Windows Forms.

If you want to access contents from another page. Then this page MUST store that piece of information inside a SESSION object and then you access that session object from a different page and get the value that you want.

Let me give you an example:

Page 1:

public string text1 = "abc";

    protected void Page_Load(object sender, EventArgs e)
    {
          Session["FirstName"] = text1;
    }

Page 2:

protected void Page_Load(object sender, EventArgs e)
{
    string text1;          
    text1 = Session["FirstName"].ToString();
}

That's how you pass values between pages that are not linked together.

Also, you can pass values using by modifying the Query string (add variables to the URL).

Example:

Page 1: (button click event)

private void btnSubmit_Click(object sender, System.EventArgs e)
{
    Response.Redirect("Webform2.aspx?Name=" +
    this.txtName.Text + "&LastName=" +
    this.txtLastName.Text);
}

Page 2:

private void Page_Load(object sender, System.EventArgs e)
{
   this.txtBox1.Text = Request.QueryString["Name"];
   this.txtBox2.Text = Request.QueryString["LastName"];
}

this is how you should pass variables between pages

Also, if you want a value to be shared between ALL visitors of your website. Then you should consider using Application instead of Session.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...