I have a DataGridView with CheckBox column, my question is how can I automatically tick the CheckBox when I select the row it belongs to? I have enabled the full row select of the DataGridView.
I have a DataGridView with CheckBox column, my question is how can I automatically tick the CheckBox when I select the row it belongs to? I have enabled the full row select of the DataGridView.
I think this is not the best solution for this problem, but this may work fine.
Properties that I've set in datagridview are:
[MultiSelect = False]
[SelectionMode = FullRowSelect]
In your datagridview_CellClick Event must add this code:
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
this.dataGridView1.Rows[e.RowIndex].Cells["colSelect"].Value = true;
}
If you're planning that it must only be clicked once then you must apply this code:
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
var count = from hasValue in dataGridView1.Rows.Cast<DataGridViewRow>()
where Convert.ToBoolean(hasValue.Cells["colSelect"].Value) == true
select hasValue;
if(count.Count() <= 0)
this.dataGridView1.Rows[e.RowIndex].Cells["colSelect"].Value = true;
}
}
Another way:
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
foreach (DataGridViewRow row in this.dataGridView1.Rows)
row.Cells["colSelect"].Value = false;
this.dataGridView1.Rows[e.RowIndex].Cells["colSelect"].Value = true;
}
}
DataGridView has an event called SelectionChanged that should fire every time a different row is selected by the user (technically, if multi select is enabled it will also fire if the selection is extended or reduced). If you attach an event handler to this you can get the currently selected row in the DGV and manipulate the value of the DataGridViewCheckBoxColumn cell.
When working with DGVs, most of the time I'm working with bound data, via a bindingsource. I generally find it more reliable to handle events raised by the bindingsource and manipulate its binding list or the underlying model, though if you're not using bound data this route will be unavailable.