General Event Handler For Runtime Buttons

R

roblaro

Hello,

I have an asp.net 2.0 app that will create a group of linkbuttons at
runtime. The ID of these links buttons will autogenerated.

I want to write a method that will be fired when any one of these buttons is
clicked. For some reason I can not figure out how to do this.

Here is some code:

Private Sub Create_Buttons()
...some code is run here to execute a stored proc and fill a datareader...
While rd.Read()
btn = New LinkButton

btn.Text = rd("CONSIGNEE_INFO").ToString() & "<br><br>"
btn.ID = rd("ADDR_ID").ToString()
btn.ForeColor = System.Drawing.Color.FromArgb(100, 51,
51, 51)
btn.Attributes.Add("style", "text-decoration: none;")
btn.Attributes.Add("onMouseOver",
"this.style.backgroundColor='#93c0ee';")
btn.Attributes.Add("onMouseOut",
"this.style.backgroundColor='#ecf0f4';")
btn.CommandName = "MyCommand"
btn.CommandArgument = rd("ADDR_ID").ToString()

...popAddr is a <div></div> layer that is set to runat="server" and
will
hold all of the runtime buttons...

popAddr.Controls.Add(btn)
End While
rd.Close()
End Sub

I thought that I would simply be able to use btn.OnCommand to pass the
method I want to execute, however, it says that its protected.

How can I get this to work?

Thanks!
 
P

Phillip Williams

Hi Bob,

Adding an event handler syntax in C# is:
btn.Command +=new CommandEventHandler(btn_Command);

Then you would write the event handling method as:
private void btn_Command(object sender, CommandEventArgs e)
{
switch(e.CommandName )
{
case "Command1":
// process command 1
break;
case "Command2":
//process command 2
break;
}
}

But the important issue here is that your controls must be created during
the page.init event handling otherwise their ViewState will not be preserved.
In other words, when the user clicks on any of those Hyperlinks nothing
will happen, unless you create those controls upon page.init.
 
R

roblaro

Phillip,

Thanks. Actually, not long after I posted this, I found the answer. You are
right about creating the buttons in the Init, which I did.

In VB.NET, to add the additional handler, I simply added the following code
to the method that creates the buttons:

AddHandler btn.Command, AddressOf Command_Button_Click

Command_Button_Click is the method I wanted to execute when any one of the
buttons was created.

This, combined with creating the buttons in the Page Init stage did the trick.

Thanks for the help.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top