【问题标题】:Use a variable in different classes in webforms c#在webforms c#的不同类中使用变量
【发布时间】:2011-10-10 09:33:58
【问题描述】:

我认为我很简单。

我有以下代码:

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.MapPath("~/") + 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)
{

}    

我想要的是用户在 button2 中执行此代码

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

我的问题是变量文件名在外面不可用

public void Button1Click(object sender, EventArgs e)

提前感谢您的帮助! 克里斯

【问题讨论】:

  • 那些不是不同的类,那些是同一类/网络表单的不同方法...

标签: c# asp.net visual-studio-2008 variables webforms


【解决方案1】:

您可以像这样在页面 ViewState 中保留变量:

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

【讨论】:

    【解决方案2】:

    上传文件时将文件名保存到SessionViewState

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

    Button2 点击处理程序中的代码,

    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();
    }  
    

    【讨论】:

    • 如果该值仅在该页面中需要,我不会使用会话。
    【解决方案3】:

    实际上在这里你可以有大量的变体:

    1. 您可以从文件上传控件中获取此值,只需使用与 Button1Click 中使用的方法相同的方法:

      string filename = Path.GetFileName(FileUpload1.FileName);
      
    2. 更准确地说,是像之前所说的那样存储在 ViewState 中。

    3. 如果您想在其他页面中使用它,只需将其保存到会话中即可。

    【讨论】:

      猜你喜欢
      • 2018-08-01
      • 2014-12-26
      • 1970-01-01
      • 1970-01-01
      • 2020-12-20
      • 2023-04-08
      • 2021-02-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多