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

ဆန္းဆန္းတင့္ (၁) ၊ ၾကြက္ကေလးနဲ႕ ကုိယ္

ကုိယ္ဟာ ဆန္းဆန္းတင့္သူတစ္ေယာက္ပါ။ အဲဒိအေၾကာင္းနဲ႕ ပတ္သတ္လုိ႕ အရင္ကေတာ့ ေပါ့ေပါ့ဆဆပါပဲ။ တျဖည္းျဖည္း ေပ်ာ္ရႊင္မွဳေတြ နည္းနည္းလာတာက...