datagridview列宽已更改

时间:2014-06-20 07:57:18

标签: vb.net datagridview column-width

我有2个datagridview。我想用鼠标更改其他datagridview的列宽度时更改datagriview列的宽度。 我尝试了这段代码,但它不起作用。

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

我通过添加mouseleave事件来编辑我的代码,但它可以正常工作。

 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

2 个答案:

答案 0 :(得分:1)

使用DataGridView1.ColumnWidthChanged事件代替ColumnMinimumWidthChanged来捕获Width更改

Private Sub DataGridView1_ColumnWidthChanged(sender As Object,
                                             e As DataGridViewColumnEventArgs) Handles DataGridView1.ColumnWidthChanged
    HeaderGrid.Columns(e.Column.Index).Width = e.Column.Width
End Sub

答案 1 :(得分:0)

我通过使用另一个事件来解决问题:

   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