Microsoft Knowledge Base Email Alertz

KBAlertz.com: This step-by-step article demonstrates how to loop through each row of an ASP.NET

Receive Microsoft Knowledge Base articles by E-Mail?

Every night we scan the Microsoft Knowledge Base. If technologies you're interested in are updated, we'll send you an e-mail. You only get one e-mail a day, and only when new articles are added.

Click here to create a
FREE account
Already have an account?
[Click here to Login]

Search KbAlertz

Advanced Search

Webmasters
Put kbAlertz on your website.
[ Click Here for more! ]





ASP.NET 2.0 Web Hosting with SQL 2005: Click Here!
Discount ASP.NET Hosting


Bug Tracking Software
For bug tracking software or defect tracking software or issue tracking software, visit Axosoft.


Community Site



We Send hundreds of thousands of emails using ASP.NET Email



Expert Web Design & Graphic Design
Design44.com




Mentioned In








Microsoft Knowledge Base Article

This article contents is Microsoft Copyrighted material.
©2005-©2007 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks




HOW TO: Loop Through and Examine CheckBox Control Values in a DataGrid Column by Using ASP.NET and Visual Basic .NET

Article ID:321881
Last Review:May 19, 2003
Revision:3.1
This article was previously published under Q321881
On This Page

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 Basic .NET

1.Start Microsoft Visual Studio .NET.
2.On the File menu, point to New, and then click Project.
3.In the New Project dialog box, click Visual Basic Projects under Project Types, and then click ASP.NET Web Application under Templates.
4.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

1.Add a new Web Form to the ASP.NET Web application as follows:
1.Right-click the project node in Solution Explorer, point to Add, and then click Add Web Form.
2.In the Name box, type MySample.aspx, and then click Open.
2.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.
3.Add a DataGrid, a Button, and a Label server control to the page as follows:
a. Drag an ASP.NET DataGrid server control from the Web Forms toolbox onto the page.
b. In the Properties window, change the ID of the DataGrid control to DemoGrid.
c. Drag an ASP.NET Button server control from the Web Forms toolbox onto the page below the DataGrid.
d. In the Properties window, change the ID of the Button control to GetSelections, and then change the Text property to Get Selections.
e. Drag an ASP.NET Label server control from the Web Forms toolbox onto the page below the Button control.
f. In the Properties window, change the ID of the Label control to ResultsInfo, and then delete any text in the Text property.
4.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="DemoGrid" runat="server" DataKeyField="CustomerID">
	<Columns>
	<asp:TemplateColumn HeaderText="Customer">
	<ItemTemplate>
	<asp:CheckBox ID="myCheckbox" Runat="server" />
	</ItemTemplate>
	</asp:TemplateColumn>
	</Columns>
</asp:DataGrid>
					
5.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:
Imports System.Data.SqlClient
Imports System.Text
					
6.Replace the existing code for the Page_Load event handler with the following code:
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If Not IsPostBack Then

            'Create a SqlConnection object.
            'Modify the connection string as necessary for your environment.
            Dim cn As SqlConnection = New SqlConnection("Server=localhost;database=Northwind;UID=sa;PWD=")

            Dim cmd As SqlCommand = New SqlCommand("SELECT * FROM Customers", cn)
            cn.Open()
            Dim reader As SqlDataReader = cmd.ExecuteReader()
            DemoGrid.DataSource = reader
            DataBind()
            reader.Close()
            cn.Close()
        End If
End Sub
					
7.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 Sub GetSelections_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GetSelections.Click
        Dim rowCount As Integer = 0
        Dim gridSelections As StringBuilder = New StringBuilder()

        'Loop through each DataGridItem, and determine which CheckBox controls
        'have been selected.
        Dim DemoGridItem As DataGridItem
        For Each DemoGridItem In DemoGrid.Items

            Dim myCheckbox As CheckBox = CType(DemoGridItem.Cells(0).Controls(1), CheckBox)
            If myCheckbox.Checked = True Then
                rowCount += 1
                gridSelections.AppendFormat("The checkbox for {0} was selected<br>", _
                                            DemoGrid.DataKeys(DemoGridItem.ItemIndex).ToString())
            End If
        Next
        gridSelections.Append("<hr>")
        gridSelections.AppendFormat("Total number selected is: {0}<br>", rowCount.ToString())
        ResultsInfo.Text = gridSelections.ToString()

End Sub
					

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

REFERENCES

For more information about the DataGrid control, click the article number below to view the article in the Microsoft Knowledge Base:
306227 (http://kbalertz.com/Feedback.aspx?kbNumber=306227/EN-US/) HOW TO: Use a CheckBox Web Control in a DataGrid in Visual Studio .NET
For more information about the DataGrid control and for samples that use this control, visit the following MSDN Web sites:
DataGrid ASP.NET QuickStart Tutorial
http://samples.gotdotnet.com/quickstart/aspplus/samples/webforms/ctrlref/webctrl/datagrid/doc_datagrid.aspx (http://samples.gotdotnet.com/quickstart/aspplus/samples/webforms/ctrlref/webctrl/datagrid/doc_datagrid.aspx)

Server-Side Data Access ASP.NET QuickStart Tutorial
http://samples.gotdotnet.com/quickstart/aspplus/doc/webdataaccess.aspx (http://samples.gotdotnet.com/quickstart/aspplus/doc/webdataaccess.aspx)

DataGrid Class
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemWebUIWebControlsDataGridClassTopic.asp (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemWebUIWebControlsDataGridClassTopic.asp)

Server-Side ASP.NET Data Binding (from the MSDN Magazine column, "Cutting Edge")
http://msdn.microsoft.com/msdnmag/issues/01/03/cutting/cutting0103.asp (http://msdn.microsoft.com/msdnmag/issues/01/03/cutting/cutting0103.asp)

DataGrid In-place Editing (from the MSDN Magazine column, "Cutting Edge")
http://msdn.microsoft.com/msdnmag/issues/01/06/cutting/cutting0106.asp (http://msdn.microsoft.com/msdnmag/issues/01/06/cutting/cutting0106.asp)

DataGrid Web Server Control
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon/html/vbconDataGridWebControl.asp (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon/html/vbconDataGridWebControl.asp)

Back to the top


APPLIES TO
Microsoft ASP.NET 1.1
Microsoft ASP.NET 1.0
Microsoft Visual Basic .NET 2003 Standard Edition
Microsoft Visual Basic .NET 2002 Standard Edition

Back to the top

Keywords: 
kbhowtomaster kbservercontrols KB321881

Back to the top

       

Community Feedback System

Very often, it takes hours to solve a problem. Very often, you've looked high and low, and have tried a lot of solutions. When you finally found it, chances are, it was because someone else helped you. Here's your chance to give back. Use our community feedback tool to let others know what worked for you and what didn't.

Please also understand that the community feedback system is not warranted to be correct, it's simply a system that we've built to let people try and help each other. If something in a feedback response doesn't make sense to you, or you're not comfortable making changes that the feedback talks about (like registry edits), please consult a professional.

Thank you for using kbAlertz.com Feedback System.

-- Scott Cate

Be the first to leave feedback, to help others about this knowledge base article.

(Optional) Name

(Optional) Public URL Or Email

Comments
No HTML -- Text Only Please