ASP: runat=server for dynamic control

Jan picture Jan · Jul 5, 2012 · Viewed 23.4k times · Source

In the Page_Load method I create a couple of controls, based on various conditions. I would like to register server side code with those controls. However, for the last part I need to declare my controls as server controls. This is normally done by runat=server, but I don't know how to set this attribute in the C# code. myControl.Attributes.Add("runat", "server") does not do the trick. This one works, meaning that the "test" method is called when I click on it:

<asp:LinkButton ID="LinkButton1" runat="server" OnClick="test">testtext</asp:LinkButton>

This one does not work:

            LinkButton lb = new LinkButton();
            lb.ID = "LinkButton1";
            lb.OnClientClick = "test";
            lb.Text = "testtext";
            lb.Attributes.Add("runat", "server");

I can click on it, and the page is loaded, but the test-method is not called.

Any hints?

Answer

Michael Liu picture Michael Liu · Jul 5, 2012

You almost got it right. Just a couple things:

  • When you manually instantiate a server control, there's no need to add the runat="server" attribute. This is a special attribute that's used only by the ASP.NET page parser to distinguish server controls from other markup.
  • The OnClick attribute in markup corresponds to the Click server-side event, which you hook up using the += operator. (On the other hand, the OnClientClick attribute in markup corresponds to the onclick client-side attribute, which typically contains a snippet of JavaScript code. The fact that OnClick doesn't correspond to onclick is admittedly a bit confusing.)

Thus:

LinkButton lb = new LinkButton();
lb.ID = "LinkButton1";
lb.Click += test;
lb.Text = "testtext";

And your event handler (which you can even make private if there are no references to it from markup):

protected void test(object sender, EventArgs e)
{
}