Microsoft KB Archive/306227

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

Article ID: 306227

Article Last Modified on 5/2/2006

-

APPLIES TO


 * Microsoft ASP.NET 1.1
 * Microsoft ASP.NET 1.0
 * Microsoft ADO.NET 1.1
 * Microsoft ADO.NET 1.0

-



This article was previously published under Q306227



IN THIS TASK
SUMMARY
 * Requirements
 * How to Add a CheckBox to a DataGrid Web Control by Using the Template Column Object
 * How to Add a CheckBox to a DataGrid Web Control by Using the User Interface (UI) and the Template Column Object
 * How to Add a CheckBox Programmatically
 * How to Iterate Through the Control to Test the Value of the CheckBox

REFERENCES



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
 Create a new ASP .NET Web application. 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. Right-click the SqlDataAdapter1 object, and then click Generate Data Set. In the Choose a DataSet area, click New. For the name, type DsAuthors . In the Choose which table(s) to add to the DataSet section, select the Authors table. Click to select the Add this DataSet to the designer check box, and then click OK to create the DataSet.  Drag a DataGrid control from the toolbox onto WebForm1, and then set the following properties for the grid: <pre class="fixed_text">  Property Name           Value -

DataSource             DsAuthors1 DataMember             Authors DataKeyField           Au_id </li>  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                   </li> Press F5 to compile and to run the program. Notice that the data is displayed in the DataGrid.</li></ol>

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: <ol> Select the DataGrid columns you want to be displayed. <ol style="list-style-type: lower-alpha;"> Right-click the DataGrid, and then click Property Builder. In the left pane, click Columns to display the Columns properties for the DataGrid.</li> Click to clear the Create columns automatically at run-time check box.</li> In the Column List section, in the Selected Columns box, add the au_id and au_lname fields.</li> Add a Template Column to the Selected Columns box, and change the Header Text to Contract. Click OK to close the Properties Builder.</li></ol> </li> Edit the ColumnTemplate and bind it to the DataSet. <ol style="list-style-type: lower-alpha;"> 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.</li> 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: <ol> Drag a CheckBox control from the toolbox into the ItemTemplate section of the Template Column.</li> Select the CheckBox control. In the Properties window, locate the DataBindings option. Click the icon to open the DataBindings dialog box.</li> In the Bindable Properties list, select Checked.</li> 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.</li> Right-click Edit Template, and then click End Template Editing to close the TemplateColumn editor and to return to the grid.</li> <li>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.</li></ol> </li></ol> </li></ol>

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. <ol> <li> 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 = &quot;CheckBox Column&quot; ' Call DynamicItemTemplate to add the child controls to the Template ' Column and bind them to the Data source. .ItemTemplate = New DynamicItemTemplate End With

DataGrid1.Columns.Add(tcol) If Not IsPostBack Then DataGrid1.DataBind End If                   </li> <li> 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(&quot;contract&quot;).GetType.ToString = &quot;System.DBNull&quot; Then oCheckBox.Checked = False Else oCheckBox.Checked = CBool(container.DataItem(&quot;contract&quot;)) End If

End Sub End Class NOTE: The binding code is commented to make the process easier to understand. </li> <li>Save and run the code. Notice that the Template Column and unbound CheckBox controls were added.</li></ol>

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

<div class="references_section">