Kristoffer Rigbolt
Kristoffer Rigbolt

Reputation:

How do I change the value of a checkbox in a DataGridView

I have appended a column of checkboxes to a DataGridView using the following:

Dim chk As New DataGridViewCheckBoxColumn
DataGridView1.Columns.Insert(0, chk)

How do I change the checked state of a particular checkbox?

I have tried using the following code:

Dim val2 As DataGridViewCheckBoxCell = DataGridView1.Item(243, i)
val2.Value = True
DataGridView1.Item(243, i) = val2

The last line resulted in runtime error "InvalidOperationException was Unhandled Cell provided already belong to a grid". Index 243 exists.

Upvotes: 2

Views: 6053

Answers (2)

Meta-Knight
Meta-Knight

Reputation: 17845

The last line is actually unneeded. Just do:

Dim val2 As DataGridViewCheckBoxCell = DataGridView1.Item(243, i)
val2.Value = True

val2 keeps a reference of the DataGridView's Cell. If you change its Value property, this change will be reflected in the user interface.

A simpler way of doing this would be:

DataGridView1.Item(243, i).Value = True

But it does the same thing.

Upvotes: 2

BFree
BFree

Reputation: 103740

I'm not that good with VB.NET but here's the C# syntax:

dataGridView1.Rows[rowIndex].Cells[columnIndex].Value = true;

Upvotes: 1

Related Questions