Dynamic Button in ASP.Net (VB)

How to create dynamic asp.net button

I. Single Button

HTML code in .aspx file

<asp:Label ID="lblHi" runat="server" Text="Hi"></asp:Label>
<div id="div1" runat = "server" width="50%"></div>

VB.Net code in code behind file

Private btnDynamic As Button

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Try
            btnDynamic = New Button
            btnDynamic.ID = "btnDynamic”
            btnDynamic.Text = "I am dynamic”
            AddHandler btnDynamic.Click, New EventHandler(AddressOf btnDynamic_Click)
            div1.Controls.Add(btnDynamic)

        Catch ex As Exception

        End Try
End Sub
Private Sub btnDynamic _Click(ByVal sender As Object, ByVal e As EventArgs)

  lblHi.Text = "You clicked me. :(


End Sub


II. Multiple Buttons (loop)

HTML code in .aspx file
<asp:Label ID="lblHi" runat="server" Text="Hi"></asp:Label>
<div id="div1" runat = "server" width="50%"></div>

VB.Net code in code behind file


Private btnDynamic As Button

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

Try
GetButtons()

Catch ex As Exception

End Try
End Sub

Protected Sub GetButtons()

Try
Dim objQry As New MyClass
Dim ds As New DataSet
Dim dt As New DataTable
Dim dr As DataRow

ds = objQry.GetButtonInformation()

If ds.Tables(0).Rows.Count > 0 Then
dt = ds.Tables(0)
For Each dr In dt.Rows
btnDynamic = New Button
btnDynamic.ID = "btn" & dr("Button_No")
btnDynamic.Text = dr("Button_Name")
AddHandler btnDynamic.Click, New EventHandler(AddressOf btnDynamic_Click)
div1.Controls.Add(btnDynamic)
Next
End If
ds.Dispose()
Catch ex As Exception

End Try

End Sub

Private Sub btnDynamic _Click(ByVal sender As Object, ByVal e As EventArgs)

Dim btn As Button = CType(sender, Button)
lblHi.Text = "You clicked button : " & btn.ID


End Sub

No comments:

Post a Comment

Penang 4D3N Free & Easy - Intro

ပီနန္က်ြန္း၊  မေလးရွားနုိင္ငံ။ ေအာက္တုိဘာ ၆ ရက္မွ ၉ ရက္။ စေန၊ တနဂၤေနြ၊ တနၤလာ၊ အဂၤါ။ ဒီလုိေတြ စီစဥ္ၾကတာ။ ဒီခရီးကေတာ့ သြားခါနီး ၂ ရက္အ...