Wine Too Wine Too - 2 months ago 9 Question

Displaying a checkbox in a databound DataGridView

I am unable to correctly populate a DataGridView checkbox column from a boolean column from a database.

First form_load code:

Me.DataGridView1.DataSource = Me.bindingSource1
GetData("SELECT myInt, myBool, myString " & _
"FROM " & myFavTable & " " & _
"WHERE (myInt > 100) ORDER BY myString")


In GetData I fill myTable with data:

Me.bindingSource1.DataSource = myTable

And finally I format grid the before showing.

I format it manually because loading is much faster than with automatic formatting.

With DataGridView1
.AllowUserToAddRows = False
.AllowDrop = False
.AllowUserToOrderColumns = False
.AllowUserToResizeRows = False
.SelectionMode = DataGridViewSelectionMode.FullRowSelect
.MultiSelect = False
.Dock = DockStyle.Fill
.EditMode = DataGridViewEditMode.EditProgrammatically

With .Columns(0)
.Name = "postN"
.HeaderText = "Postal"
.Width = 55
End With

With .Columns(1) 'here should be a checkbox
.Width = 20
End With

With .Columns(2)
.Name = "colCity"
.HeaderText = "City"
.Width = 180
End With
End With

But with this code, in my column that should show checkboxes the string value
is displayed when in database is

How in this situation can I get checkboxes in the middle column instead of text?

I try with .Columns.Add... before and after binding but with no wanted results.

That way I can get
, but in the new column.


In design-time add the columns to the DataGridView and set the middle column as a CheckBoxColumn.

Then set:

With DataGridView1
   .AutoGenerateColumns = False

Edit: I see the problem now. You need to set the DataPropertyName to be the same as the column.

When you add columns to the DataGridView, in that dialog set the DataPropertyName to match the DataTable (myTable) column Names. That's the magic behind the mapping.

enter image description here

Here is the code:

DataTable dt = new DataTable();
DataRow dr = dt.NewRow();
dr[0] = "Hello";
dr[1] = false;
dr = dt.NewRow();
dr[0] = "World";
dr[1] = true;
dataGridView1.DataSource = dt;

enter image description here