Programmatically add a linkbutton with onclick event

Its easy to write a linkbutton into an aspx page like so:

<asp:LinkButton ID="lbDate" runat="server" Text="Click Me" OnClick="lbDate_click" CommandArgument="1" />

But how do I dynamically create one?  The Onclick method is protected and cannot be set programmatically.  Here's what I'm trying to do...

[using vb]

For i = 0 To 9
  Dim lbDate As LinkButton = New LinkButton
  lbDate.ID = "lb" & i
  lbDate.Text = "Test " & i
  lbDate.Onclick = "lbDate_click"   'Doesn't work, onclick is protected.  HELP!
  lbDate.CommandArgument = i
Who is Participating?
I really apologise for this

I got all confused between VB.NET and C#.NET

This is final and correct

AddHandler lbDate.Click, AddressOf Me.lbDate_click
lbDate.Click += new System.EventHandler(this.lbDate_click);
osubvrAuthor Commented:
Sorry, now I feel stupid.

I neglected to mention that I'm using the .NET Framework 2.0beta.

When I use your example, I get the following error:

Compiler Error Message: BC32022: 'Public Event Click(sender As Object, e As System.EventArgs)' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event.

Source Error:

Line 137:            lbDate.CommandArgument = DateAdd(DateInterval.Day, -i, Date.Today)
Line 138:            lbDate.Text = DateAdd(DateInterval.Day, -i, Date.Today)
Line 139:            lbDate.Click += New System.EventHandler(this.lbDate_click)

osubvrAuthor Commented:
Oops.  On this server we're still on .net2.0alpha... Microsoft .NET Framework Version:2.0.40607.42

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.