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?
You almost got it right. Just a couple things:
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.OnClickattribute in markup corresponds to theClickserver-side event, which you hook up using the+=operator. (On the other hand, theOnClientClickattribute in markup corresponds to theonclickclient-side attribute, which typically contains a snippet of JavaScript code. The fact thatOnClickdoesn’t correspond toonclickis admittedly a bit confusing.)Thus:
And your event handler (which you can even make
privateif there are no references to it from markup):