ASP: runat=server for dynamic control

喜你入骨 提交于 2019-11-29 16:38:35

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

Are you trying to register server side event? If so you can do like this.

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

Event

protected void LinkButton1_Click(object sender, EventArgs e)
{ 

}

You don't need to. Since the controls are created on the server side via C# code, they are already server-side controls. The problem you are experiencing has to do with the page life cycle: when you create a control on the server side as you are doing now, you need to re-add the control on every postback and rehook any event handlers that you want to handle for them.

Also note that your code shows 2 different things: on the markup that you posted, you are displaying a handler for the OnClick event whereas on the C# code you are adding a handler for the OnClientClick event. They are 2 different things. The OnClientClick event simply fires any javascript code that you have on your page when the control is clicked. It's exactly the same as doing this:

 link.Attributes.Add("onclick","SomeJavascriptFunction();");

First off, you don't need that lb.Attributes.Add("runat", "server") line. All runat="server" does is make the control visible to the code-behind. Since you're adding the control in the code-behind, that's a moot point.

As for the script, note that the one that works is using OnClick and your broken one is using OnClientClick. The difference is important because OnClick is natively understood by javascript, and it will find the function with the name test and execute it.

OnClientClick, on the other hand, is arbitrary javascript that the ASP.NET runtime binds to the click event manually. Meaning, it's just going to execute test. That's nothing. test(), on the other hand, is proper javascript.

So, change that line to lb.OnClickClick = "test()";

edit: I mixed myself up, see the other answer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!