Click here to Skip to main content
15,889,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello House,

Please does anyone know how to loop through datagrid that has checkbox column, and get values for the rows that are checked?

I can do this in web forms using gridview control with this code:

C#
int rowCount = 0;
            foreach ( DataGridItem DemoGridItem in DemoGrid.Items )
            {
                CheckBox myCheckbox = ( CheckBox ) DemoGridItem.Cells[0].Controls[1];
                if ( myCheckbox.Checked == true )
                {
                    rowCount++;
                    
                }
            }


Please how do i implement the above code in C# Windows application? Thanks in advance.
Posted

1 solution

Updated:

C#
int rowCount = 0;
foreach (DataGridViewRow row in DemoGrid.Rows)
{
   DataGridViewCheckBoxCell cell = row.Cells[colCheck] as DataGridViewCheckBoxCell;

   if ( cell!=null && !DBNull.Value.Equals( cell.Value ) && ( bool ) cell.Value == true )
        {
            //Your code here
        }
}
 
Share this answer
 
v3
Comments
Uwakpeter 11-Aug-14 11:29am    
How do i get the selected checkboxes rows from the datagrid and which should i use this in?
Trung Nguyen Son 11-Aug-14 11:34am    
It's up to your design: where you put the checkbox column.
In this case, the colCheck is the first one.
DataGridViewCheckBoxCell cell = row.Cells[0] as DataGridViewCheckBoxCell;
Uwakpeter 11-Aug-14 11:57am    
i am using the checkbox name instead of index,and it is working, i meant i want to be able to extract selected row record(s)(cell values of the selected rows) and stored it variables. Thanks
Trung Nguyen Son 11-Aug-14 12:01pm    
You're welcome!
Pls mark this question as answered if it works for you!
Happy coding!
Uwakpeter 11-Aug-14 12:11pm    
not working yet, i meant i want to be able to extract/retrieve selected row record(s)(cell values of the selected rows) and stored it variables.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900