I\'ve added a checkbox column to a DataGridView in my C# form. The function needs to be dynamic - you select a customer and that brings up all of their items that could be s
If your column has been already created due to binding with a recordset of BIT type, the type of the column will be text anyway. The solution I have found is to remove that column and replace it with a DataGridViewCheckBoxColumn
having the same binding data.
DataGridViewColumn oldCol = dgViewCategory.Columns["mycolumn"];
int chkIdx = oldCol.Index;
DataGridViewCheckBoxColumn chkCol = new DataGridViewCheckBoxColumn();
chkCol.HeaderText = oldCol.HeaderText;
chkCol.FalseValue = "False";
chkCol.TrueValue = "True";
chkCol.DataPropertyName = oldCol.DataPropertyName;
chkCol.Name = oldCol.Name;
dgViewCategory.Columns.RemoveAt(chkIdx);
dgViewCategory.Columns.Insert(chkIdx, chkCol);
1) How do I make it so that the whole column is "checked" by default?
var doWork = new DataGridViewCheckBoxColumn();
doWork.Name = "IncludeDog" //Added so you can find the column in a row
doWork.HeaderText = "Include Dog";
doWork.FalseValue = "0";
doWork.TrueValue = "1";
//Make the default checked
doWork.CellTemplate.Value = true;
doWork.CellTemplate.Style.NullValue = true;
dataGridView1.Columns.Insert(0, doWork);
2) How can I make sure I'm only getting values from the "checked" rows?
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.IsNewRow) continue;//If editing is enabled, skip the new row
//The Cell's Value gets it wrong with the true default, it will return
//false until the cell changes so use FormattedValue instead.
if (Convert.ToBoolean(row.Cells["IncludeDog"].FormattedValue))
{
//Do stuff with row
}
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
DataGridViewCheckBoxCell ch1 = new DataGridViewCheckBoxCell();
ch1 = (DataGridViewCheckBoxCell)dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0];
if (ch1.Value == null)
ch1.Value=false;
switch (ch1.Value.ToString())
{
case "True":
ch1.Value = false;
break;
case "False":
ch1.Value = true;
break;
}
MessageBox.Show(ch1.Value.ToString());
}
best solution to find if the checkbox in the datagridview is checked or not.
If you try it on CellContentClick
Event
Use:
dataGridView1.EndEdit(); //Stop editing of cell.
MessageBox.Show("0 = " + dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
To test if the column is checked or not:
for (int i = 0; i < dgvName.Rows.Count; i++)
{
if ((bool)dgvName.Rows[i].Cells[8].Value)
{
// Column is checked
}
}
Here's a one liner answer for this question
List<DataGridViewRow> list = DataGridView1.Rows.Cast<DataGridViewRow>().Where(k => Convert.ToBoolean(k.Cells[CheckBoxColumn1.Name].Value) == true).ToList();