How can I connect up my UserControl properties in such a way that they retain state on postback?

会有一股神秘感。 提交于 2020-01-25 07:15:45

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/15393525/how-can-i-connect-up-my-usercontrol-properties-in-such-a-way-that-they-retain-st

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!