Click here to Skip to main content
Click here to Skip to main content
Go to top

Selecting multiple checkboxes in a DataGrid control

, 4 Aug 2004
Rate this:
Please Sign up or sign in to vote.
How to select multiple checkboxes in a DataGrid control.

Introduction

In this article, I will explain how to select multiple checkboxes which are inside a DataGrid web server control.

foreach(DataGridItem dgi in myGrid.Items) 
{ 
    CheckBox myCheckBox = (CheckBox)dgi.Cells[0].Controls[1];
    if(myCheckBox.Checked == true)
    {
        name+= myGrid.DataKeys[dgi.ItemIndex].ToString();
        name+=",";
    }
}

Explanation

In the code, myGrid refers to a DataGrid. All the code provided is placed inside the ItemCommand Event of the DataGrid control. First, we iterate through the DataGrid items using the foreach loop.

foreach(DataGridItem dgi in myGrid.Items)

In the body of the foreach loop, we assign our newly created instance of CheckBox the value of the checkbox presented in the DataGrid control. Which in this case lies in the first column of the DataGrid.

CheckBox myCheckBox = (CheckBox)dgi.Cells[0].Controls[1];

After that, we check that if the checkbox has been checked or not, using a simple if statement.

if(myCheckBox.Checked == true)

Once we find out that the checkbox has been checked, we use the DataKeys property of the DataGrid control to get the appropriate value from the checked row. In this case, I have set the DataKeys property to name, getting name value in my string name variable.

name+= myGrid.DataKeys[dgi.ItemIndex].ToString();

You should always assign some primary key value to the DataKeys collection so that you can always retrieve more data with that value.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

azamsharp
Web Developer
United States United States
I am the founder of knowledge base website, HighOnCoding, GridViewGuy, RefactorCode.com and ScreencastADay.com.
 
HighOnCoding is a website which will get you high legally with useful information. There are tons of articles, videos and podcasts hosted on HighOnCoding.
 
HighOnCoding.com www.HighOnCoding.com
 

My Blog:

Blog

 

Buy my iPhone app ABC Pop

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web01 | 2.8.140921.1 | Last Updated 5 Aug 2004
Article Copyright 2004 by azamsharp
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid