Saturday, May 16, 2009

How to Add Dynamic Buttons,Images in asp.net ?

Today i had the necessity to add some dynamic buttons to a page based on a SQL Server 2005 table. Basically i've a Dataset that return to me Functions based on the user logged in.
This code can be easily changed to do different things (like menu\treeview).

So my Goal was to have a page that build up n buttons based on some info that returns from the DB, and each buttons has an handler so to do\call different pages or do different things when pressing each button.

First of all i created a new webusercontrol called ctButtonPanel and overrided the Render method as follow :


Public Overrides Sub RenderControl(ByVal writer As System.Web.UI.HtmlTextWriter)
For Each objControl As Web.UI.WebControls.Button In Me.Controls
writer.AddStyleAttribute("padding", "10px") 'Spacing buttons
writer.RenderBeginTag(HtmlTextWriterTag.Div) 'Put buttons inside DIV
objControl.RenderControl(writer) 'Write the control (button in this case)
writer.RenderEndTag() 'close the DIV
Next
End Sub


You can do whatever there. I wanted the button to appears vertically and spaced.
Once created the webusercontrol just put a reference in the page that should load your items





Then on the server side of the page we just iterate trough our Dataset with function infos and add a new button(or whatever webcontrol) to the CommandPanel as follow :

'Important - clear the webusercontrol each time.
Me.CommandPanel.Controls.Clear()
'Instanciate the control (in my case a button is enough)
Dim mybutton As Button
For Each row As DataRow In value.Tables(0).Rows 'my Dataset
mybutton = New Button
mybutton.Text = row("sCodice") 'my Function Text
mybutton.ID = row("nIDSceltaLavorazioneOperatore") 'my Function ID
mybutton.Height = Unit.Pixel(30)
mybutton.Width = Unit.Pixel(200)
mybutton.CssClass = "BTN_Submit_Lavorazione"
AddHandler mybutton.Click, AddressOf BottoneClick
Me.CommandPanel.Controls.Add(mybutton) 'Add the just created button
Next


And add the Handler that will be called by the created buttons once clicked as follow

Private Sub BottoneClick(ByVal sender As Object, ByVal e As System.EventArgs)
Dim myBtn As Button = sender
'Here i used the button ID to do different things. ID are distinct functionID in my 'case so was enough.
'You can add Arguments when creating the button and retryve the arguments from here

select case myBtn.id
case 1
case 2
case 3
case 4
end select

end sub


And here is a quick sample of what i got.


Hope it can helps.
Ciao

2 comments:

Anonymous said...

Hi, can you please give an example on how to use the CommandArgument?
Thanks , Jly

MdO said...

Hi,
well in the building function where you have
mybutton.ID = row you can add a new value
mybutton.CommandArgument= 'your argument here'
and then retrive it from the onClick handler using simply myBtn.CommandArgument

Hope it helps.
Ciao

Post a Comment