开发者

Best way to do user control code behind?

I have this very simple control below. And on the page that i use this control I'd just like to be able to say: ucMessagePanel.SetMessage(...), but it does not allow me to declare a static method. I tried doing it with Static properties and that works just fine, but shouldn't I also be able to use static methods?

    <center>
    <asp:Panel ID="pnlMessage" runat="server" >
        <asp:Label ID="lblMessage" runat="server" />
    </asp:Panel>
</center>


public partial class ucMessagePanel : System.Web.UI.UserControl
{        
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    public static void SetMessage(string message, string mssgCssClass)
    {
        lblMessage.Text = message;
        pnl开发者_运维问答Message.CssClass = mssgCssClass;
    }
}


You don't need static methods. When you declare the user control in the ASPX page, you can reference it directly by the ID.

In the ASPX:

<uc:SomeUserControl ID="UserControl1" runat="server" ...>

And in the code behind:

UserControl1.SetMessage("Some message");

In the user control, change the method to something like this:

public void SetMessage(string Message)
{
    lblMessage.Text = Message;
}


Static methods can't access items contained on an instance of the control. For example; if you had two concurrent requests running; and you call the static method; which instance of the ucMessagePanel class would it modify (this even bypassing the issue of the code provided couldn't compile)?

There is no way you should have been able to edit those controls with a static property either, unless you were taking the value of the static property and assigning it to the control using an instance method.

You should avoid using static in ASP.NET request processing unless it is something you need to share between request threads.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜