-1

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.

SniperLegacy
  • 139
  • 5

1 Answers1

1

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

Ctznkane525
  • 7,297
  • 3
  • 16
  • 40
  • I tried it and I have the same behavior as described. The checkbox cell does not display the square and I cannot interact with it. The only thing I changed was to replace the insert call for the add call. – SniperLegacy Jan 31 '18 at 20:10
  • 1
    Do you have any custom painting code on the grid ? – Ctznkane525 Jan 31 '18 at 20:22
  • You actually help me figured it out. In the painting event, the DataGridViewCellPaintingEventArgs had the property Hanled set to true at the end. That cause my problem. I will update my post to include it in case it can help others and I will mark the post answered and your post as the answer. Thank you ! – SniperLegacy Jan 31 '18 at 20:49
  • Awesome...glad to help – Ctznkane525 Jan 31 '18 at 20:55