I have a WinForm application that has DataGridView with one column with CheckBox. After selecting few rows with the checkbox I need to iterate rows and check if the CheckBox is ticked or not.
I have tried woth for and foreach loop but everytime the value of the bx is true! What's funny is that I have a button that select all and another that's clearing all using the code, and it works!
My code for creating the DataGridView:
ComputerSelection computerSelection = new ComputerSelection();
DataGridViewCheckBoxColumn checkBox = new DataGridViewCheckBoxColumn();
checkBox.ValueType = typeof(bool);
checkBox.Name = "CheckBox";
checkBox.HeaderText = "Select";
computerSelection.compGridView.Columns.Add(checkBox);
computerSelection.compGridView.Columns.Add("Name", "Name");
computerSelection.compGridView.Columns.Add("AgentVersion", "Agent Version");
computerSelection.compGridView.Columns.Add("Status", "Status");
computerSelection.compGridView.Columns.Add("Domain", "Domain");
Code for iterating (that most of the posts that i searched sharing that solution as the correct one):
foreach (DataGridViewRow row in computerSelection.compGridView.Rows)
{
if ((bool)row.Cells["CheckBox"].Value)
{
computerSelection.ComputersList.Add(row.Cells[1].Value.ToString());
}
}
This code ALWAYS return TRUE even on an unchecked checkboxes. I searched so much posts on StackOverFlow, even tried to use the as DataGridViewCheckBoxCell but without success.
the selecting all button code (That uses the same mechanism :():
private void SelectAllButton_Click(object sender, EventArgs e)
{
for (int i = 0; i < compGridView.Rows.Count; i++)
{
compGridView.Rows[i].Cells[0].Value = true;
}
}
I need that after every iteration the "row.Cells[1].Value.ToString()" code will return false or true, not always true.