Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

asp.net - ASP: runat=server for dynamic control

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)
{
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...