Microsoft KB Archive/320707

= How to loop through and examine CheckBox control values in a DataGrid column by using ASP.NET and Visual C# .NET =

Article ID: 320707

Article Last Modified on 3/29/2007

-

APPLIES TO


 * Microsoft ASP.NET 1.1
 * Microsoft ASP.NET 1.0
 * Microsoft Visual C# .NET 2003 Standard Edition
 * Microsoft Visual C# .NET 2002 Standard Edition

-



This article was previously published under Q320707





For a Microsoft Visual Basic .NET version of this article, see 321881.

This article refers to the following Microsoft .NET Framework Class Library namespaces:
 * System.Data.SqlClient
 * System.Text

In this task

 * SUMMARY
 * Requirements
 * Create an ASP.NET Web Application by Using Visual C# .NET
 * Create the Sample Web Form Page
 * Verify That It Works
 * REFERENCES



SUMMARY
This step-by-step article demonstrates how to loop through each row of an ASP.NET DataGrid control and how to determine if the ASP.NET CheckBox server control that is used to identify the row has been selected.

The sample code in this article uses the Microsoft SQL Server Northwind database to populate the DataGrid control and then adds a CheckBox server control to the initial column for each row. This is a common technique that allows users to select multiple, specific rows in a DataGrid.

back to the top

Requirements

 * Microsoft Windows 2000 Professional, Windows 2000 Server, Windows 2000 Advanced Server, or Windows XP Professional
 * Microsoft .NET Framework
 * Microsoft Internet Information Services (IIS)
 * Microsoft Visual Studio .NET

back to the top

Create an ASP.NET Web application by using Visual C# .NET
 Start Microsoft Visual Studio .NET. On the File menu, point to New, and then click Project. In the New Project dialog box, click Visual C# Projects under Project Types, and then click ASP.NET Web Application under Templates. In the Location box, replace the WebApplication  default name with MyWebApp. If you are using the local server, you can leave the server name as http://localhost. The resulting Location box appears as follows:

http://localhost/MyWebApp



back to the top

Create the sample Web Form page
 Add a new Web Form to the ASP.NET Web application as follows:  Right-click the project node in Solution Explorer, point to Add, and then click Add Web Form.</li> In the Name box, type MySample.aspx, and then click Open.</li></ol> </li> In the Properties window, change the pageLayout property for the document to FlowLayout. Although you do not have to do this to use the sample code, this will make the presentation appear cleaner.</li> Add a DataGrid, a Button, and a Label server control to the page as follows:  Drag an ASP.NET DataGrid server control from the Web Forms toolbox onto the page.</li> In the Properties window, change the ID of the DataGrid control to DemoGrid .</li> Drag an ASP.NET Button server control from the Web Forms toolbox onto the page below the DataGrid.</li> In the Properties window, change the ID of the Button control to GetSelections, and then change the Text property to Get Selections .</li> Drag an ASP.NET Label server control from the Web Forms toolbox onto the page below the Button control.</li> In the Properties window, change the ID of the Label control to ResultsInfo, and then delete any text in the Text property.</li></ol> </li>  Switch to HTML view in the editor. Add the code to the default DataGrid template to construct the columns. The resulting code for the control should appear as follows: <asp:DataGrid id=&quot;DemoGrid&quot; runat=&quot;server&quot; DataKeyField=&quot;CustomerID&quot;> <Columns> <asp:TemplateColumn HeaderText=&quot;Customer&quot;> <ItemTemplate> <asp:CheckBox ID=&quot;myCheckbox&quot; Runat=&quot;server&quot; /> </ItemTemplate> </asp:TemplateColumn> </Columns> </asp:DataGrid> </li>  Right-click the page, and then click View Code. This opens the code-behind class file in the editor. Add the following namespace references to the code-behind class file: using System.Data.SqlClient; using System.Text; </li>  Replace the existing code for the Page_Load event handler with the following code: private void Page_Load(object sender, System.EventArgs e) { if(!IsPostBack) {       //Create a SqlConnection object. //Modify the connection string as necessary for your environment. SqlConnection cn = new SqlConnection(&quot;Server=localhost;database=Northwind;UID=sa;PWD=&quot;); SqlCommand cmd = new SqlCommand(&quot;SELECT * FROM Customers&quot;,cn); cn.Open; SqlDataReader reader = cmd.ExecuteReader; DemoGrid.DataSource = reader; DataBind; reader.Close; cn.Close; }

}                   </li>  Switch to Design view, and then double-click GetSelections. This opens the code-behind class file in the editor. Replace the existing code in the GetSelections_Click event handler with the following code: private void GetSelections_Click(object sender, System.EventArgs e) { int rowCount = 0; StringBuilder gridSelections = new StringBuilder;

//Loop through each DataGridItem, and determine which CheckBox controls //have been selected. foreach(DataGridItem DemoGridItem in DemoGrid.Items) {       CheckBox myCheckbox = (CheckBox)DemoGridItem.Cells[0].Controls[1]; if(myCheckbox.Checked == true) {           rowCount++; gridSelections.AppendFormat(&quot;The checkbox for {0} was selected &quot;,                        DemoGrid.DataKeys[DemoGridItem.ItemIndex].ToString); }   }    gridSelections.Append(&quot; &quot;);

gridSelections.AppendFormat(&quot;Total number selected is: {0}&quot;, rowCount.ToString); ResultsInfo.Text = gridSelections.ToString; }                     </li></ol>

back to the top

Verify that it works

 * 1) On the File menu, click Save All to save the Web Form and other files that are associated with the project.
 * 2) On the Build menu in the Visual Studio .NET integrated development environment (IDE), click Build Solution.
 * 3) In Solution Explorer, right-click the Web Form page (MySample.aspx), and then click View in Browser. Notice that the page displays the data in the grid. Additionally, a check box appears in the first column of each row. The user can click to select this check box to mark specific rows.
 * 4) Click to select a few of the check boxes for the rows, and then click Get Selections.

After the page makes a round trip to the server and executes the code in the GetSelections_Click event handler, a list of the items that you selected in the previous step appears. The code in the GetSelections_Click event handler loops through each DataGridItem in your ASP.NET DataGrid server control, determines whether the Checked property of the related CheckBox control is true, and then records the associated key value at that specific position for the DataKeys of the DataGrid.

back to the top

<div class="references_section">