开发者

Use a variable in different classes in webforms c#

开发者 https://www.devze.com 2023-04-12 10:56 出处:网络
I am stack in something simple i think. I have the following code: public void Button1Click(object sender, EventArgs e)

I am stack in something simple i think.

I have the following code:

public void Button1Click(object sender, EventArgs e)
{
    if (FileUpload1.HasFile)
    {
        if (FileUpload1.PostedFile.ContentType == "text/xml")
            {

                    string filename = Path.GetFileName(FileUpload1.FileName);
                    FileUpload1.SaveAs(Server.MapPat开发者_运维技巧h("~/") + filename);
                    StatusLabel.Text = "Upload status: File uploaded!";

                    DataSet ds = new DataSet();
                    ds.ReadXml((Server.MapPath(filename)));
                    GridView1.DataSource = ds;
                    GridView1.DataBind();
            }
            else
                StatusLabel.Text = "Only xml files are accepted!";

    }
}

public void Button2_Click1(object sender, EventArgs e)
{

}    

What i want is the user the execute this code in button2

                    DataSet ds = new DataSet();
                    ds.ReadXml((Server.MapPath(filename)));
                    GridView1.DataSource = ds;
                    GridView1.DataBind();

My problem is that the variable filename is not available outside

public void Button1Click(object sender, EventArgs e)

Thanks in advance for your help! Chris


you can persist the variable in the page ViewState like this:

private string fileName
{
    get { return ViewState["fileName"] != null ? (string)ViewState["fileName"] : String.Empty; }
    set { ViewState["fileName"] = value; }
}


Save the filename into Session or ViewState while uploading a file.

public void Button1Click(object sender, EventArgs e)
{
    ..
    string filename = Path.GetFileName(FileUpload1.FileName);
    ...
    Session["filename"]=filename;
}

Code in Button2 click handler,

public void Button2_Click1(object sender, EventArgs e)
{
 if(Session["filename"]!=null)
 { 
  string filename=Session["filename"].ToString();
  DataSet ds = new DataSet();
  ds.ReadXml((Server.MapPath("~/" + filename)));
  GridView1.DataSource = ds;
  GridView1.DataBind();
}  


Actually here you can have huge amount of variants:

  1. You can get this value from file upload control, juts simply using same method as it was used in Button1Click:

    string filename = Path.GetFileName(FileUpload1.FileName);
    
  2. More correctly, is to store in ViewState as it was told before.

  3. If you want to use this in other pages, just save this to session.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号