Adding checkbox to datagridview column header, not aligning properly
This is my first entry, but I think this is what youre looking for. I tested it and it worked on my datagrid. You were using the width for the rectangle, youll need it for the column width instead. I set the column header to 4, but you would replace the 4 with your column you want to use I put it in two ways, one with a four loop, the other just as single lines. Tell me if this worked for you:
Dim rect As Rectangle = DataGridView1.GetCellDisplayRectangle(4, -1, True) ' replace 4
rect.Y = 3
Dim sum = DataGridView1.Columns(0).Width
'for this area write a for loop to find the width of each column except for the last line which you manually do
'
'
'For i As Integer = 1 To 4 - 1 Step 1 ' replace 4
'sum = sum + DataGridView1.Columns(i).Width
'Next
sum = sum + DataGridView1.Columns(1).Width
sum = sum + DataGridView1.Columns(2).Width
sum = sum + DataGridView1.Columns(3).Width
' stop here and add the last line by hand here
sum = sum + (DataGridView1.Columns(4).Width / 2) + 35 ' used in both cases ' replace 4
rect.X = sum
checkboxHeader231 = New CheckBox()
With checkboxHeader231
.BackColor = Color.Transparent
End With
checkboxHeader231.Name = "checkboxHeader1"
checkboxHeader231.Size = New Size(18, 18)
checkboxHeader231.Location = rect.Location
AddHandler checkboxHeader231.CheckedChanged, AddressOf checkboxHeader231_CheckedChanged
DataGridView1.Controls.Add(checkboxHeader231)
Robin L
Updated on June 04, 2022Comments
-
Robin L almost 2 years
Im trying to add a checkbox to a specific datagridview column header, I found some code online to help but it's not aligning properly and I'm not really sure how to fix it.
Below is an image of the problem and the code, any help would be greatly appreciated!
P.S. I think it might be something to do with properties but I've played around with them but not been successful.
Private checkboxHeader231 As CheckBox Private Sub show_chkBox() Dim rect As Rectangle = DataGridView1.GetCellDisplayRectangle(columnIndexOfCheckBox, -1, True) ' set checkbox header to center of header cell. +1 pixel to position rect.Y = 3 rect.X = rect.Location.X + 8 + (rect.Width / 4) checkboxHeader231 = New CheckBox() With checkboxHeader231 .BackColor = Color.Transparent End With checkboxHeader231.Name = "checkboxHeader1" checkboxHeader231.Size = New Size(18, 18) checkboxHeader231.Location = rect.Location AddHandler checkboxHeader231.CheckedChanged, AddressOf checkboxHeader231_CheckedChanged DataGridView1.Controls.Add(checkboxHeader231) End Sub Private Sub checkboxHeader231_CheckedChanged(sender As System.Object, e As System.EventArgs) Dim headerBox As CheckBox = DirectCast(DataGridView1.Controls.Find("checkboxHeader1", True)(0), CheckBox) For Each row As DataGridViewRow In DataGridView1.Rows row.Cells(columnIndexOfCheckBox).Value = headerBox.Checked Next End Sub