How do you automatically resize columns in a DataGridView control AND allow the user to resize the columns on that same grid?

后端 未结 24 3061
孤城傲影
孤城傲影 2020-11-29 18:03

I am populating a DataGridView control on a Windows Form (C# 2.0 not WPF).

My goal is to display a grid that neatly fills all available width with cells - i.e. no un

24条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-29 18:48

    I had to do this in VB and prefer to split it out to a method that I placed in a Module. You can add the Fill column as another ByRef parameter if desired.

    ''' 
    ''' Makes all columns in a DataGridView autosize based on displayed cells,
    ''' while leaving the column widths user-adjustable.
    ''' 
    ''' A DataGridView to adjust
    Friend Sub MakeAdjustableAutoSizedGridCols(ByRef dgv As DataGridView)
        Dim width As Integer
    
        For Each col As DataGridViewColumn In dgv.Columns
            col.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
            width = col.Width
            col.AutoSizeMode = DataGridViewAutoSizeColumnMode.None
            col.Width = width
        Next
        dgv.AllowUserToResizeColumns = True
    End Sub
    

提交回复
热议问题