Saturday, November 3, 2012

How to create template columns dynamically in a grid view


Sample Program:

Imports System.Data
Imports System.Web.UI.WebControls
Public Class MyCustomTemplate
    Implements ITemplate
    Public Sub InstantiateIn(ByVal container As System.Web.UI.Control) Implements System.Web.UI.ITemplate.InstantiateIn
        Dim cb As New CheckBox()
        cb.ID = "PageID"
        AddHandler cb.DataBinding, AddressOf CheckBox_DataBining
        container.Controls.Add(cb)
    End Sub
    Public Sub CheckBox_DataBining(ByVal sender As Object, ByVal e As EventArgs)
        Dim button As CheckBox = TryCast(sender, CheckBox)
        Dim container As GridViewRow = CType(button.NamingContainer, GridViewRow)
        Dim dataValue As Object = DataBinder.Eval(container.DataItem, "id")
        If Not IsDBNull(dataValue) Then
            button.Text = dataValue.ToString()
        End If
    End Sub
End Class
Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub _Default_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        Dim tf As New TemplateField()
        tf.HeaderText = "Custom Template Field Column"
        tf.ItemTemplate = New MyCustomTemplate()
        gvoutput.Columns.Add(tf)
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            Dim dt As New DataTable

            dt.Columns.Add("id", GetType(Long))
            dt.Rows.Add(1)
            dt.Rows.Add(2)
            dt.Rows.Add(3)
            dt.Rows.Add(4)

            gvoutput.DataSource = dt
            gvoutput.DataBind()

        End If
    End Sub
  
    Protected Sub btnsubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnsubmit.Click
        Try
            Dim a As Long = 0

            For i As Integer = 0 To gvoutput.Rows.Count - 1
                Dim row As GridViewRow = gvoutput.Rows(i)
                Dim isChecked As Boolean = CType(row.FindControl("PageID"), CheckBox).Checked
                If isChecked Then
                    a = a + 1
                End If
            Next

            Response.Write(a)
        Catch ex As Exception

        End Try
        
    End Sub
End Class

No comments: