Dynamic GridView Checkbox Column at runtime
Even there are various ways to add check boxes to the GridView, the following way I am going to explain is very neat and may not simple if it is used in only one place but consider reusing it. It actually reduces a lot of duplication inside the code.
Adding Checkbox Column at runtime dynamically to GridView
While adding CheckboxColumn at runtime, we need to consider following the same hierarchy as the TemplateField. So we must create a TemplateField. Add respective templates such as ItemTemplate, EditItemTemplate, and HeaderTemplate. In our case we are trying only ItemTemplate for making explanations simpler. And adding these objects should happen at Form.Init Event.
After adding these objects, the main object is our custom template which is CheckBoxTemplate. This class is responsible for creating and data binding the Checkboxes into the column.
Adding Checkbox Column at design time to GridView
While adding Checkbox column at design time is easier and you can attach attributes to the Checkbox directly at markup. There are times the Checkbox has to be created at runtime. If this is the case then this article is written focused on that. However the following is the sample of “Adding Checkbox Column at design time “
<asp:TemplateField >
<ItemTemplate>
<asp:CheckBox runat="server" ID="chkCheck"
Checked='<%# eval("Discontinued") %>' />
</ItemTemplate>
</asp:TemplateField>
CheckBoxTemplate Custom Template for CheckBox
This CheckBoxTemplate gets ColumnName as input for fetching the data. This can be either by constructor’s parameter or as a property. This class must implement ITemplate to behave as a custom template. If the ITemplate is implemented it has to implement InstantiateIn method.
InstantiateIn from ITemplate
This is the function actually the checkbox gets created in. After the creation the control has to be bound to the data. DataBinding event has to be handled for filling up the data for the checkbox. The data can be fetched from the GridViewRow’s DataItem Object.
Checked Changed Event
You have to raise an event from the template and use the handler from the webpage to handle respectively.
Register the event
Event CheckBoxCheckedChanged(ByVal sender As CheckBox, ByVal e As EventArgs)
Add the handler
AddHandler CheckBoxItem.CheckedChanged, AddressOf CheckBoxItem_CheckedChanged
Raise the event
Private Sub CheckBoxItem_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
RaiseEvent CheckBoxCheckedChanged(sender, e)
End Sub
Handle the event
Protected Sub CheckboxColumn_CheckBoxCheckedChanged(ByVal sender As CheckBox, _
ByVal e As System.EventArgs) _
Handles CheckboxColumn.CheckBoxCheckedChanged
Dim CurrentCheckBox = DirectCast(sender, CheckBox)
Response.Write(CurrentCheckBox.Checked)
End Sub
Source Code
MarkUp(.Aspx)
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="ProductName" />
</Columns>
</asp:GridView>
</form>
</body>
</html>
Code Behind(.vb)
Imports System.Data.SqlClient
Imports System.Data
Partial Class _Default
Inherits System.Web.UI.Page
Private WithEvents CheckboxColumn As CheckBoxTemplate
Private ReadOnly Property ConnectionString() As String
Get
Return "Server=.\SQLEXPRESS;Database=NorthWind;Trusted_Connection=True"
End Get
End Property
Private ReadOnly Property Connection() As SqlConnection
Get
Dim ConnectionToFetch As New SqlConnection(ConnectionString)
ConnectionToFetch.Open()
Return ConnectionToFetch
End Get
End Property
Public Function GetData() As DataTable
Dim SelectQry = "select * from Products"
Dim SampleSource As New DataSet
Try
Dim SampleDataAdapter As New SqlDataAdapter(SelectQry, ConnectionString)
SampleDataAdapter.Fill(SampleSource)
Catch ex As Exception
Throw ex
End Try
Return SampleSource.Tables(0)
End Function
Protected Sub form1_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles form1.Init
CreateCheckBoxColumn()
End Sub
Protected Sub form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles form1.Load
If (Not IsPostBack) Then
LoadGrid()
End If
End Sub
Private Sub LoadGrid()
GridView1.DataSource = GetData()
GridView1.DataBind()
End Sub
Private Sub CreateCheckBoxColumn()
Dim TemplatedColumn As New TemplateField()
CheckboxColumn = New CheckBoxTemplate("Discontinued")
TemplatedColumn.ItemTemplate = CheckboxColumn
GridView1.Columns.Add(TemplatedColumn)
End Sub
Protected Sub CheckboxColumn_CheckBoxCheckedChanged(ByVal sender As CheckBox, _
ByVal e As System.EventArgs) _
Handles CheckboxColumn.CheckBoxCheckedChanged
Dim CurrentCheckBox = DirectCast(sender, CheckBox)
Response.Write(CurrentCheckBox.Checked)
End Sub
End Class
Template Class(.vb)
Imports Microsoft.VisualBasic
Public Class CheckBoxTemplate
Implements ITemplate
Private m_ColumnName As String
Event CheckBoxCheckedChanged(ByVal sender As CheckBox, ByVal e As EventArgs)
Public Property ColumnName() As String
Get
Return m_ColumnName
End Get
Set(ByVal value As String)
m_ColumnName = value
End Set
End Property
Public Sub New()
End Sub
Public Sub New(ByVal ColumnName As String)
Me.ColumnName = ColumnName
End Sub
Private Sub InstantiateIn(ByVal ThisColumn As System.Web.UI.Control) _
Implements ITemplate.InstantiateIn
Dim CheckBoxItem As New CheckBox()
CheckBoxItem.ID = "Chk" & ColumnName
CheckBoxItem.AutoPostBack = True
AddHandler CheckBoxItem.DataBinding, AddressOf CheckBoxItem_DataBinding
AddHandler CheckBoxItem.CheckedChanged, AddressOf CheckBoxItem_CheckedChanged
ThisColumn.Controls.Add(CheckBoxItem)
End Sub
Private Sub CheckBoxItem_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
RaiseEvent CheckBoxCheckedChanged(sender, e)
End Sub
Private Sub CheckBoxItem_DataBinding(ByVal sender As Object, ByVal e As EventArgs)
Dim CheckBoxItem As CheckBox = DirectCast(sender, CheckBox)
Dim CurrentRow As GridViewRow = DirectCast(CheckBoxItem.NamingContainer, GridViewRow)
Dim CurrentDataItem As Object = DataBinder.Eval(CurrentRow.DataItem, ColumnName)
If Not CurrentDataItem Is DBNull.Value Then
CheckBoxItem.Checked = Convert.ToBoolean(CurrentDataItem)
End If
End Sub
End Class