How do I add a check box to a Web Forms DataGrid?
If you are binding a column to a logical field, Visual Studio automatically adds a checkbox to the Web Forms DataGrid column for you. However, if you want to add a non-data bound check box to a Web Forms DataGrid, in the current version of Visual Studio you need to manually edit the HTML.
For example, here is the HTML for a DataGrid containing a single data-bound column that was built using the Visual Studio grid builder.
<asp:DataGrid id="DataGrid1" runat="server" AutoGenerateColumns="False"> <Columns> <asp:BoundColumn DataField="OrderID" HeaderText="Order ID"></asp:BoundColumn> </Columns> </asp:DataGrid></P>
To add a non-data bound checkbox to this grid, you can add a TemplateColumn control. The <HeaderTemplate> element specifies the text to appear in the column header. The <ItemTemplate> element specifies the column control is a checkbox:
<asp:DataGrid id="DataGrid1" runat="server" AutoGenerateColumns="False"> <Columns> <asp:TemplateColumn> <HeaderTemplate> Select </HeaderTemplate> <ItemTemplate> <mm:mmCheckBox ID="checkboxSelect" Runat="server"></mm:mmCheckBox> </ItemTemplate> </asp:TemplateColumn> <asp:BoundColumn DataField="OrderID" HeaderText="Order ID"></asp:BoundColumn> </Columns> </asp:DataGrid></P>
When you run the form, your DataGrid should look something like this:
Responding to the CheckBox Click
If you want to respond to the user clicking the check box, do the following:- View the form in HTML mode and add the OnCheckChanged attribute to the check box, specifying the name of the method to be called. You must also set the AutoPostBack attribute to true. For example:
<mm:mmcheckbox id="chkSelect" Runat="server" OnCheckChanged="Check_Clicked" AutoPostBack="true" Width="30px"></mm:mmcheckbox>
- Add the method you specified in the OnCheckChanged attribute to the form (if it doesn't already exist).
For example, in C#:
private void Check_Clicked(object sender, System.EventArgs e) { // Get a reference to the checkbox CheckBox chkItem = (CheckBox)sender; // Get a reference to the current item DataGridItem GridItem = (DataGridItem)chkItem.NamingContainer; }And in VB .NET:
Private Sub Check_Clicked(ByVal sender As Object, ByVal e As System.EventArgs) ' Get a reference to the checkbox Dim chkItem As CheckBox = CType(sender, CheckBox) ' Get a reference to the current item Dim GridItem As DataGridItem = CType(chkItem.NamingContainer, DataGridItem) End Sub
The first line of code converts the sender object to a CheckBox. The second line of code gets the currently selected item by means of the CheckBox's NamingContainer property. Given this information, you can add code to this method that handles the event.
© (c) 2026 Oak Leaf Enterprises, Inc., 1996-2026 • Updated: 04/26/18
Comment or report problem with topic
