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

Categories

0 votes
1.3k 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...