Groups | Blog | Home
all groups > asp.net webcontrols > november 2005 >

asp.net webcontrols : General Event Handler For Runtime Buttons


roblaro
11/4/2005 1:39:02 PM
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!

--
Bob Gibilaro
Phillip Williams
11/4/2005 2:30:03 PM
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.

--
HTH,
Phillip Williams
http://www.societopia.net
http://www.webswapp.com


[quoted text, click to view]
roblaro
11/4/2005 2:41:08 PM
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.

--
Bob Gibilaro
Applications Developer


[quoted text, click to view]
AddThis Social Bookmark Button