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
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.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)
{
}
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();");
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)
{
}
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.