saas

saas

  • NA
  • 8
  • 17.2k

How to tick multiple checkboxes in the datagridview using C#

Mar 23 2012 12:37 AM
Hi there,

I need to enable the end user to tick several checkboxes in the datagridview of my C# application at the same time, using the checkbox_checkChanged event, when they have used the mouse to first highlight the cells they require.
So basically the end user will use their mouse to highlight cells in the datagridview, then click on the checkbox2, which should then tick the checkbox in each row that they have highlighted a cell.

Here is my code which displays a window that states how many rows/cells have been selected. I then need to tick each checkbox in the datagridview which has a highlighted cell in that row. Currently it will display the window recording which rows/cells have been selected, then when clicking the OK button it ticks every checkbox in the datagridview instead of just the checkboxes that have a highlighted cell in that row.

private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            Int32 selectedCellCount = dgv2.GetCellCount(DataGridViewElementStates.Selected);
            if (selectedCellCount > 0)
            {
                if (dgv2.AreAllCellsSelected(true))
                {
                    MessageBox.Show("All cells are selected", "Selected Cells");
                }
               
                else
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();

                    for (int i = 0;
                        i < selectedCellCount; i++)
                    {
                        sb.Append("Row: ");
                        sb.Append(dgv2.SelectedCells[i].RowIndex.ToString());
                        sb.Append(", Column: ");
                        sb.Append(dgv2.SelectedCells[i].ColumnIndex.ToString());
                        sb.Append(Environment.NewLine);
                    }


                    sb.Append("Total: " + selectedCellCount.ToString());
                    // confirmation
                    MessageBox.Show(sb.ToString(), "Selected Cells");

                    foreach (DataGridViewRow row in dgv2.Rows)
                    {
                        row.Cells[2].Value = checkBox2.Checked && String.IsNullOrEmpty(row.Cells[0].ErrorText);
                    }

                }
            }
        }

Please help...

Answers (1)