Link to home
Start Free TrialLog in
Avatar of esko_user
esko_user

asked on

Get the selected checkboxs count on click in Datagridview

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

ASKER CERTIFIED SOLUTION
Avatar of ajitha75
ajitha75
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial