Question

In an ASP.NET Webforms application I have a submission form containing a UserControl with properties as such:

    public string Name
    {
        get
        {
            String s = (String)ViewState["Name"];
            return ((s == null) ? String.Empty : s);
        }

        set
        {
            ViewState["Name"] = value;
        }
    }

This is adapted from an MSDN walk-through. This is assumed to be "bound" (not databinding as I don't think that's possible) to the contents of a text box defined in the ascx as below:

  <asp:TextBox runat="server" ID="name" />

The question is, what is the best practice for allowing this to be accessible as a public property, and retain state on postback?

Was it helpful?

Solution

The simplest option is to have the public properties on your UserControl delegate to the properties of the child controls:

public string Name
{
   get { return name.Text; }
   set { name.Text = value; }
}

The TextBox will then take care of maintaining the state on postback.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top