简体   繁体   English

aspx.cs文件中的变量范围

[英]Scope of variables in aspx.cs file

I am writing following code: 我正在编写以下代码:

namespace WebApplication5
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        private DataSet dataset1 = new DataSet();
        OleDbDataAdapter adapter;

        public DataSet ds
        {
            get { return dataset1; }
            set { dataset1 = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            OleDbConnection con = new OleDbConnection();
            con.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\jayant\Documents\User_Details.accdb";
            con.Open();
            adapter = new OleDbDataAdapter("Select * from User_Details",con);
            adapter.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.DataBind();
           //  ds.WriteXml("C:\\MyUser_Details.xml"); If I do this here it writes data
            con.Close();
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            ds.WriteXml("C:\\MyUser_Details.xml");
            // no data in xml files, just root tags
        }
    }
}

Here my DataSet variable is global but when I am clicking on button2, it sends no data to the Ouput XML file. 在这里,我的DataSet变量是全局变量,但是当我单击button2时,它不会将任何数据发送到Ouput XML文件。 Can you please tell me why? 你能告诉我为什么吗? Or what modifications shall I make to perform this? 或我应对此进行哪些修改?

Thanks 谢谢

You need to have a look at Asp.net page life cycle , In your code when you click on your button page is destroyed and re created again and whole life cycle is followed and in that process your ds(dataset) is recreated too, therefore output xml doesn't have any data in it. 您需要查看Asp.net页面的生命周期 ,在您单击按钮页面的代码中,该页面被破坏并再次创建,并遵循整个生命周期,在此过程中,您还将重新创建ds(dataset),因此输出xml中没有任何数据。 To maintain state of your dataset have a look at State Management in Asp.net 要维护数据集的状态,请查看Asp.net中的“状态管理”

It is because you create a new Dataset during postback. 这是因为您在回发期间创建了新的数据集。

move the initialization of the Dataset private DataSet dataset1= new DataSet(); 移动数据集private DataSet dataset1= new DataSet();的初始化private DataSet dataset1= new DataSet();

in to the Load 进入负载

protected void Page_Load(object sender, EventArgs e)
    {
         if(!Page.IsPostBack) { dataset1= new DataSet(); }
    }

and obviously, don`t forget to click Button1 before you click Button2 :) 很明显,不要忘记在单击Button2之前先单击Button1 :)

Yes you are partially correct that your ds is Global but only for life time of Web Page. 是的,您部分正确地认为您的ds是Global,但仅在Web页面的生命期内有效。 Once the page is rendered and sent to client, your page is disposed and hence with it the variable. 页面呈现并发送给客户端后,您的页面将被处理,并因此带有变量。

If you want to ds to be available in button_click event, either populate it inside Page_Load event 如果您希望ds在button_click事件中可用,请在Page_Load事件中填充它

protected void Page_Load(object sender, EventArgs e)
{ 
           OleDbConnection con = new OleDbConnection();
           con.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\jayant\Documents\User_Details.accdb";
            con.Open();
            adapter = new OleDbDataAdapter("Select * from User_Details",con);
            adapter.Fill(ds);
            con.close();
}

Or generate the dataset in your Button_Click event handler. 或在Button_Click事件处理程序中生成数据集。

If you do not want to generate this data set every time, you have to either keep this variable in Session or ViewState or Cache 如果您不想每次都生成此数据集,则必须将此变量保留在SessionViewStateCache中

UPDATE 1 更新1

The third and last option could be to make this dataset variable as class level variable ie static and it would be available all the time 第三个也是最后一个选择是使此数据集变量成为类级别的变量,即静态变量,并且始终可用

You don't get Data in the dataset in button2_click because button1_click and button2_clicks are entirely different requests to the server. 在button2_click中的数据集中不会获得数据,因为button1_click和button2_clicks是对服务器的完全不同的请求。 And asp.net does not persists data stored in variables between requests. 而且,asp.net不会在请求之间持久存储存储在变量中的数据。 If you need to persist data you should use any State Management techniques provided by asp.net, like Session or Viewstate or Caching. 如果需要保留数据,则应使用asp.net提供的任何状态管理技术,例如Session或Viewstate或Caching。

I suggest please use ViewState as Session will consume lot of server memory, though you can use any one of them to solve the purpose. 我建议您使用ViewState因为Session将消耗大量服务器内存,尽管您可以使用其中任何一个来解决目的。

I don't think button1's event handler is doing anything apart from creating ds. 我认为button1的事件处理程序除了创建ds之外没有做任何其他事情。 So only one event handler will solve the purpose. 因此,只有一个事件处理程序可以解决目的。

Another way to access ds in both the event handlers without losing data is declare ds as static . 在两个事件处理程序中访问ds而不丢失数据的另一种方法是将ds声明为static But this mechanism does not suit this scenario. 但是这种机制不适合这种情况。

 protected void Button1_Click(object sender, EventArgs e)
    {
        OleDbConnection con = new OleDbConnection();
        con.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\jayant\Documents\User_Details.accdb";
        con.Open();
        adapter = new OleDbDataAdapter("Select * from User_Details",con);
        adapter.Fill(ds);
        GridView1.DataSource = ds;
        Session.Add("Dataset", ds); //Adding Session here
        GridView1.DataBind();
        con.Close();
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        DataSet ds = (DataSet)Session["Dataset"]; //Retrieving Value from session
        ds.WriteXml("C:\\MyUser_Details.xml");
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM