Help with adding checkbox column to DataGridView in window form
ado.net, vb.net, winforms
Solution
Add new column in the properties of the DataGridView by:
- Choosing Columns from properties panel and double click on it
- then choose " Add... " button
- then set the new column as " Unbound Column "
- Give it a name and choose its type " DataGridViewCheckBoxColumn "
- Set the header you want and make sure that " read only " is not selected.
that's it.
(If the database field (in SQL Server) is of type 'bit' then the the datagridview automatically maps it to the datagridview as a checkbox instead of a textbox. No coding necessary.)
Problem
I am trying to add a checkbox column to a DataGridView in a simple window forms application. I am pulling back some data from a database using ADO.NET, putting into a datatable, and then setting the datagridview datasource to the datatable. I then want to add a checkbox column as the second column. So far I have this code that seems to work: ``` ' Code here to connect to database Dim da As New SqlDataAdapter(cmd) Dim dt As New DataTable da.Fill(dt) MainForm.MyDataGridView.DataSource = dt Dim ChkBox As New DataGridViewCheckBoxColumn ChkBox.FlatStyle = FlatStyle.Standard MainForm.MyDataGridView.Columns.Insert(1, ChkBox) ``` This code 'works' and I get MyDataGridView to show the data with the checkbox column in the correct position in the table. However, for some reason, I cannot check any of the check boxes in the DataGridView? I have tried lots of things (e.g.altering the readonly state of the column) but cannot get it to work. Is there something obvious that I am missing?