saas saas - 3 months ago 42
C# Question

How to check multiple checkboxes in the datagridview using C#

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...

Answer

I see your code is from here: http://msdn.microsoft.com/en-us/library/x8x9zk5a.aspx but instead of this:

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

You need to follow what the article says, here this will point you in the right direction:

for (int i = 0; i < selectedCellCount; i++)
{
dataGridView1.SelectedCells[i].Value = true;
}
Comments