Domanda

I have two pages. first.aspx and second.aspx. In order to get all the control values from first.aspx, i added directive to second.aspx

<%@ PreviousPageType VirtualPath="~/PR.aspx" %>

I have no problem to get all the previous page controls and set it to labels, but i have a big problem to save those values to a private variable, and reuse it after page load event is done. Here is code example. when i try to get the value from input in another method, it has nothing added. Why?

    public partial class Second : System.Web.UI.Page
        {        
            List<string> input = new List<string>();
            protected void Page_Load(object sender, EventArgs e)
            {
                    if (Page.PreviousPage != null&&PreviousPage.IsCrossPagePostBack == true)
                    {
                        TextBox SourceTextBox11 (TextBox)Page.PreviousPage.FindControl("TextBox11");
                        if (SourceTextBox11 != null)
                        {
                            Label1.Text = SourceTextBox11.Text;
                            input.Add(SourceTextBox11.Text);
                        }
                     }
              }

            protected void SubmitBT_Click(object sender, EventArgs e)
        {
                  //do sth with input list<string>
                  //input has nothing in it here.
         }
       }
È stato utile?

Soluzione

The SubmitBT_Click-click event happens in a postback. But all variables (and controls) are disposed at the end of the page's lifecycle. So you need a way to persist your List, e.g. in the ViewState or Session.

public List<String> Input
{
    get
    {
        if (Session["Input"] == null)
        {
           Session["Input"] = new List<String>();
        }
        return (List<String>)Session["Input"]; 
    }
    set { Session["Input"] = value; }
}

Nine Options for Managing Persistent User State in Your ASP.NET Application

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top