counting how many rows in a datagrid are checked

fguihen

Junior Contributor
Joined
Nov 10, 2003
Messages
248
Location
Eire
I have many many rows added to a datagrid. there is a checkbox in the first column of each row. i need to be able to extract the data for each checked row, and also count all the checked rows. does anyone know how to do this. i added the check box in the column properties of the datagrid in the visual studio designer, in case that matters.
 
Hi,

If your datagrid's datasource is an DataTable, you can use a DataView to filter rows and have the rows Count. Example:
Code:
DataView dv = new DataView((DataTable)yourDataGrid.DataSource,"CheckedColumnName = True        ", "CheckedColumnName",DataViewRowState.CurrentRows);

int checkedRowsCounter = dv.Count;
Console.WriteLine(string.Format("Checked Rows = {0}",checkedRowsCounter ));

OR

you can spend more time and code and write a FOR EACH statement instead like:

Code:
            int counter = 0;

            foreach(DataGridViewRow dr in myDataGridView.Rows)
            {
                if ((bool)dr.Cells["myCheckBoxColumnName"].Value == true)
                {
                    counter++;
                }
            }

            //output
            Console.WriteLine(counter.ToString());

i hope it helps,

Best Regards,
Tiago Teixeira
 
Back
Top