Search code examples
vb.netdatagridviewcolumn-width

datagridview column width changed


I have 2 datagridview .I want to change width of a column of datagriview while I'm changing the width of a column of the other datagridview with the mouse. I tried this code but it doesn't work.

Private Sub DataGridView1_ColumnMinimumWidthChanged(sender As Object, e As System.Windows.Forms.DataGridViewColumnEventArgs) Handles DataGridView1.ColumnMinimumWidthChanged
    HeaderGrid.Columns(e.Column.Index).Width = e.Column.Width
End Sub

I edited my code by adding a mouseleave event and it works but not properly.

 Private Sub DataGridView1_MouseLeave(sender As Object, e As System.EventArgs) Handles DataGridView1.MouseLeave
    Dim c As DataGridViewColumn = DataGridView1.Columns(DataGridView1.CurrentCell.ColumnIndex)
    Dim h As DataGridViewColumn = HeaderGrid.Columns(DataGridView1.CurrentCell.ColumnIndex)
    h.Width = c.Width
End Sub

enter image description here


Solution

  • I resolved the problem by using another event:

       Private Sub DataGridView1_CellMouseLeave(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellMouseLeave
        If e.ColumnIndex <> -1 And HeaderGrid.ColumnCount <> 0 Then
            Dim c As DataGridViewColumn = DataGridView1.Columns(e.ColumnIndex)
            Dim h As DataGridViewColumn = HeaderGrid.Columns(e.ColumnIndex)
            h.Width = c.Width
        End If
    End Sub