welcome Netizen

Share Your Knowledge.It is a way to achieve immortality

Friday, May 4, 2012

Add dynamic button control in gridview or add dynamic column and button in gridview

Here to create control dynamically in 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
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
    End Sub

Sub loadde()
         'Here write the code Bind the data into dt
        Dim bnd As New BoundField
        bnd.HeaderText = "Phone"
        bnd.DataField = "Number"
        Dim bnd1 As New BoundField
        bnd1.HeaderText = "Name"
        bnd1.DataField = "Name"
        Dim bnd2 As New BoundField
        bnd1.HeaderText = "Control"
        GridView1.DataSource = dt
    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"
    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
    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


Post a Comment