You are currently offline, waiting for your internet to reconnect

HOW TO: Use a CheckBox Web Control in a DataGrid in Visual Studio .NET

This article was previously published under Q306227
SUMMARY
Use this step-by-step guide to add a CheckBox control to a DataGrid control and bind it to the Authors table in the Microsoft SQL Server Pubs database.

In Visual Studio .NET Web Forms, you can add controls to the DataGrid by using the TemplateColumn object.

back to the top

Requirements

The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
  • Microsoft Windows 2000 Professional, Microsoft Windows 2000 Server, Microsoft Windows 2000 Advanced Server, or Microsoft Windows NT 4.0 Server
This article assumes that you are familiar with the following topics:
  • The DataGrid control, data retrieval, and data binding on Web forms
  • Microsoft Visual Studio .NET
  • Microsoft SQL Server
back to the top

How to Add a CheckBox to a DataGrid Web Control by Using the TemplateColumn Object

  1. Create a new ASP .NET Web application.
  2. In Server Explorer, create a connection to the SQL Server Pubs database. Drag the Authors table from Server Explorer onto WebForm1 to create SqlConnection1 and SqlDataAdapter1 objects.
  3. Right-click the SqlDataAdapter1 object, and then click Generate Data Set.
  4. In the Choose a DataSet area, click New. For the name, type DsAuthors.
  5. In the Choose which table(s) to add to the DataSet section, select the Authors table.
  6. Click to select the Add this DataSet to the designer check box, and then click OK to create the DataSet.
  7. Drag a DataGrid control from the toolbox onto WebForm1, and then set the following properties for the grid:
       Property Name           Value   -----------------------------   DataSource              DsAuthors1   DataMember              Authors   DataKeyField            Au_id					
  8. Add the following code to the Page_Load event to fill the DataSet and to bind the DataGrid to the DataSet:
    SqlDataAdapter1.Fill(DsAuthors1)If Not IsPostBack Then    DataGrid1.DataBind()End If					
  9. Press F5 to compile and to run the program. Notice that the data is displayed in the DataGrid.
back to the top

How to Add a CheckBox to a DataGrid Web Control by Using the User Interface (UI) and the TemplateColumn Object

After the initial setup is completed, add a CheckBox control to the DataGrid, and bind it to the DataSet. To do this, follow these steps:
  1. Select the DataGrid columns you want to be displayed.
    1. Right-click the DataGrid, and then click Property Builder. In the left pane, click Columns to display the Columns properties for the DataGrid.
    2. Click to clear the Create columns automatically at run-time check box.
    3. In the Column List section, in the Selected Columns box, add the au_id and au_lname fields.
    4. Add a Template Column to the Selected Columns box, and change the Header Text to Contract. Click OK to close the Properties Builder.
  2. Edit the ColumnTemplate and bind it to the DataSet.
    1. Right-click the DataGrid, and then click Edit Template, Columns[2] - Contract to open the template editor.

      The template editor has four sections: HeaderTemplate, ItemTemplate, EditItemTemplate, and FooterTemplate. You will use the ItemTemplate section.
    2. Use the ItemTemplate property to control the appearance of a data item in the TemplateColumn. To do this, create a template that defines how the item is displayed in the column:
      1. Drag a CheckBox control from the toolbox into the ItemTemplate section of the Template Column.
      2. Select the CheckBox control. In the Properties window, locate the DataBindings option. Click the icon to open the DataBindings dialog box.
      3. In the Bindable Properties list, select Checked.
      4. In the Simple Bound section, in the Container, DataItem list, select Contract. Click OK.

        The check portion of the CheckBox control will be bound to the Contracts field, but the text portion of the CheckBox control will not be bound and will appear blank.
      5. Right-click Edit Template, and then click End Template Editing to close the TemplateColumn editor and to return to the grid.
      6. Save and test the application. Notice that the Contract column is displayed as a check box, and its properties reflect the data from the Authors table in the SQL Server Pubs database.
back to the top

How to Add a CheckBox Programmatically

The following sample code adds the TemplateColumn and CheckBox controls to the grid and binds the data programmatically. First, the sample code adds a TemplateColumn control and then adds the check boxes to the Template column. Finally, the code adds an event handler to bind the CheckBox control to the database.
  1. Type or paste the following code sample in the Page_Load event. The code creates a TemplateColumn object and sets its header text.
    SqlDataAdapter1.Fill(DsAuthors1)'Create a new TemplateColumn object.Dim tcol As New TemplateColumn()With tcol    .HeaderText = "CheckBox Column"    ' Call DynamicItemTemplate to add the child controls to the Template     ' Column and bind them to the Data source.        .ItemTemplate = New DynamicItemTemplate()End WithDataGrid1.Columns.Add(tcol)If Not IsPostBack Then     DataGrid1.DataBind()End If					
  2. Type or paste the following code after the Public Class WebForm1, End class.
    Public Class DynamicItemTemplate    ' ITemplate - When implemented by a class, defines the Control object    ' to which child controls and templates belong. These child controls     ' are in turn defined within an inline template.    Implements ITemplate    Public Overridable Overloads Sub InstantiateIn(ByVal container As Control) Implements ITemplate.InstantiateIn        ' InstantiateIn - When implemented by a class, defines the Control         ' object to which child controls and templates belong. These child         ' controls are, in turn, defined within an inline template.        '         ' Create an instance of a CheckBox object.        Dim oCheckBox As CheckBox = New CheckBox()        ' When the DataBinding event of the CheckBox fires, call the sub         ' BindCheckBox to properly bind.          ' AddHandler oCheckBox.DataBinding, AddressOf BindCheckBox        'Add the CheckBox to the controls collection.        container.Controls.Add(oCheckBox)    End Sub    Public Sub BindCheckBox(ByVal sender As Object, ByVal e As EventArgs)        'Create a new instance of a CheckBox.         Dim oCheckBox As CheckBox = CType(sender, CheckBox)        Dim container As DataGridItem = CType(oCheckBox.NamingContainer, DataGridItem)        'Evaluate the data from the Grid item and set the Checked property         ' appropriatly        If container.DataItem("contract").GetType.ToString = "System.DBNull" Then            oCheckBox.Checked = False        Else            oCheckBox.Checked = CBool(container.DataItem("contract"))        End If    End SubEnd Class						
    NOTE: The binding code is commented to make the process easier to understand.
  3. Save and run the code. Notice that the Template Column and unbound CheckBox controls were added.


back to the top

How to Iterate Through the Control to Test the Value of the CheckBox

Uncomment the following line of code in the aforementioned code sample:
  'AddHandler oCheckBox.DataBinding, AddressOf BindCheckBox				
This line calls the event handler, Public Sub BindCheckBox, when the DataBinding event of the CheckBox control executes. The BindCheckBox procedure evaluates the data and properly sets the Checked property of the current check box. Notice that the procedure is called for every row in the grid as the DataGrid binds each row.

back to the top
REFERENCES
For more information, click the following article numbers to view the articles in the Microsoft Knowledge Base:
316649 How to use the Server Explorer in Visual Studio .NET and Visual Studio 2005
308656 HOW TO: Open a SQL Server Database by Using the SQL Server .NET Data Provider with Visual Basic .NET
307860 INFO: ASP.NET Data Binding Overview
308485 HOW TO: Create a Master/Detail Page with Web Form Controls
317878 PRB: DataGrid Web Server Control Does Not Display "<" and ">" Characters Correctly
back to the top
Properties

Article ID: 306227 - Last Review: 05/02/2006 04:04:38 - Revision: 3.4

Microsoft ASP.NET 1.1, Microsoft ASP.NET 1.0, Microsoft ADO.NET 1.1, Microsoft ADO.NET 1.0

  • kbhowtomaster KB306227
Feedback