Get the selected checkboxs count on click in Datagridview

esko_user
esko_user used Ask the Experts™
on
I need to get the count of the check boxes which are selected, in a datagridview.

I have added the check box column through code,
DataColumn colSelection = new DataColumn();
 colSelection.DataType = System.Type.GetType("System.Boolean");
 colSelection.ColumnName = "Select";
 this.objdatatable.Columns.Add(colSelection);
 this.dataGridViewResources.DataSource = this.objdatatable;

To get the count i have called a method on the cellContentClick event . Please refer the below code. The code gives me correct count when the check boxes are selected. But if i unCheck the check boxes the count is not correct (as chkActive.Selected  remains true even if i uncheck the check box)

any suggestions?



//method call on cell content click event 
private void dataGridViewResources_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0)
            {
                string selectedCount = this.GetSelectedCount();
                lblSelectedCount.Text = selectedCount;
            }
        }

//method which returns the count of the check box selected
 private string GetSelectedCount()
        { 
            try
            {
                for (int i = 0; i <= dataGridViewResources.Rows.Count - 1; i++)
                {                  
                    DataGridViewCheckBoxCell chkActive = (DataGridViewCheckBoxCell)dataGridViewResources.Rows[i].Cells[0];
                    if (chkActive.Selected == true)
                    {                   
                        selectedCount = selectedCount + 1;                    
                    }                   
                }
            }
            catch (Exception ex)
            {                
            }
            return selectedCount.ToString();  
        }

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
Please make the below changes.....

1. Handle CurrentCellDirtyStateChanged event of the GridView...

        private void dataGridViewResources_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            dataGridViewResources.CommitEdit(DataGridViewDataErrorContexts.Commit);

        }

2. change the line...

if (chkActive.Selected == true)

to

 if (Convert.ToInt32(chkActive.Value) == 1)

3. Make sure the "DataGridViewCheckBoxColumn" has TrueValue set to 1 and FalseValue set to 0.

-Ajitha

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial