Search code examples
c#winformsdatagridviewdatagridviewcheckboxcell

DataGridViewCheckBoxColumn does not display CheckBoxCell for all rows


I have been trying for few hours to add a DataGridViewCheckBoxColumn to an existing DataGridView with the designer and through code. The CheckBoxCell is not displaying the square (or state) on the UI. However, when I tried some code that I found (and forgot to change the index), I got it working and displaying normally.

So I am wondering why you cannot use a DataGridViewCheckBoxColumn at the last index of the DataGridView.Columns ?


To be more explicit:

Why does this work

MyDataGridView.Columns.Insert(0, myCheckBoxColumn);

When this does not work

MyDataGridView.Columns.Insert(7, myCheckBoxColumn);

Note: The myCheckBoxColumn variable did not change between the two lines. It is exactly the same and is irrelevant to the actual problem.


Edit:

Using the Add method like bellow does not solve the problem.

MyDataGridView.Columns.Add(myCheckBoxColumn);

Resolved:

My problem was related to the handling of the CellPainting event of the DataGridView. At the end of the function, the property Handled of the DataGridViewCellPaintingEventArgs was set to true. This was causing the DataGridViewCheckBoxColumn to not display properly.


Solution

  • If you want to add a column to the right, use the Add method of DataGridViewColumnCollection instead:

    MyDataGridView.Columns.Add(myCheckBoxColumn);
    

    https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcolumncollection.add(v=vs.110).aspx