Click here to Skip to main content
15,906,766 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I'm working with DataGridView. My questions are;
1. How to check if the rows are checked. For example, I have 5 rows, 2nd row and 4th row are checked. What I need is showing 2 and 4 (the index of each checked rows).
2. Above, there are 2 checked rows. How to count them?

The data is retrieved from sql server database through dataTable and DataAdapter and the checkBox column is added manually in Column Collection Properties.
Here's my code and it's not working properly
C#
private void setTidakAktifToolStripMenuItem_Click(object sender, EventArgs e)
{
    for (int i = 0; i < this.gridUser.Rows.Count -1; i++)
    {
        int c = 0;
        //if (Convert.ToBoolean(this.gridUser.Rows[i].Cells["ColCheckBox"].Value) == true) //not working
        DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)this.gridUser.Rows[i].Cells["ColCheckBox"];
        if (Convert.ToBoolean(chk.Value) == true)
            c++;
    }
    //also not working
    //foreach (DataGridViewRow row in this.gridUser.Rows)
    //{
    //    if (Convert.ToBoolean(((DataGridViewCheckBoxCell)row.Cells["ColCheckBox"]).Value) == true)
    //        c++;
    //}
    //MessageBox.Show(c.ToString());
}
Posted
Updated 17-Apr-12 21:40pm
v2

1 solution

dim chk as new checkbox

while a<datagrid.rows.count>
chk=ctype(datagrid.rows(a).cell(1).controls[1],CheckBox)
if chk.checked then
your operation
end if
 
Share this answer
 
Comments
derodevil 18-Apr-12 4:00am    
Where do you get .Controls[1] property? It's coded in C#. Of course it throws exception if I write
CheckBox chk = new CheckBox(); int c = 0;
while (c != this.gridUser.Rows.Count)
{
chk = (CheckBox)this.gridUser.Rows[c].Cells[1].Controls[1];
if (chk.Checked)
c++;
}

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