Here to create control dynamically in asp.net. Also to apply
the click event for created control in grid view.
In a previous post i have written to create control in
normal page,
Now here going add in grid view control. In many cases we
need to work with dynamic data, in that case dynamic control is needed.
Here i illustrate with an example to dynamically add a button
control in asp.net
I start the sample code with page init event..
In that page init event we need to bind the data value in
grid view. So here I write the function to get the data from database..
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
loadde()
End Sub
|
Sub loadde()
'Here write
the code Bind the data into dt
Dim bnd As New BoundField
bnd.HeaderText = "Phone"
bnd.DataField = "Number"
GridView1.Columns.Add(bnd)
Dim bnd1 As New BoundField
bnd1.HeaderText = "Name"
bnd1.DataField = "Name"
GridView1.Columns.Add(bnd1)
Dim bnd2 As New BoundField
bnd1.HeaderText = "Control"
GridView1.Columns.Add(bnd2)
GridView1.DataSource = dt
GridView1.DataBind()
End Sub
|
Next we have to add the below code in data bound event .In
that below code describe to add new button in each row in grid view….
Protected Sub
GridView1_DataBound(ByVal sender As Object, ByVal e As
System.EventArgs) Handles
GridView1.DataBound
For Each row As GridViewRow In GridView1.Rows
Dim lnk As New LinkButton
lnk.Text = "button"
lnk.ID = "lnkbtn"
lnk.CommandName = "update"
row.Cells(2).Controls.Add(lnk)
Next
End Sub
|
Here we mention command name as update, when button click on grid view Row updating event will be fired
Here the code for Row updating event….
Protected Sub
GridView1_RowUpdating(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridView1.RowUpdating
Dim row1 As GridViewRow = GridView1.Rows(e.RowIndex)
usrname = row1.Cells(0).Text
MsgBox(usrname)
End Sub
|
When every button clicks the row updating event is fired.
Also by adding handler to the button we used to fire the button outside click
event. For that to add the code in data bound event
AddHandler lnk.Click, AddressOf
lnk_click
Protected Sub
lnk_click(ByVal sender As
Object, ByVal e
As EventArgs)
End Sub
I hope you like this articles………….
Happy programming
0 comments:
Post a Comment