Stuart Helwig Stuart Helwig - 1 year ago 152
C# Question

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

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 unused (dark grey) areas down the right and sizes each column appropriately according to the data it contains, but also allows the user to resize any of the columns to their liking.

I am attempting to achieve this by setting the AutoSizeMode of each column to be DataGridViewAutoSizeColumnMode.AllCells except for one of the columns which I set to DataGridViewAutoSizeColumnMode.Fill in order to ensure the entire area of the grid is neatly filled with data. (I don't mind that when the user attempt to resize this column it springs back to a size that ensures the horizontal space is always used.)

However, as I mentioned, once loaded I would like to allow the user to resize the columns to suit their own requirements - in setting these AutoSizeMode values for each column it appears the user is then unable to then resize those columns.

I've tried not setting the AutoSizeMode of all the columns which does allow resizing BUT doesn't set the initial size according to the data the cells contain. The same result occurs when changing the grid's AutoSizeMode back to "Not Set" after loading the data.

Is there a setting I'm missing here which allows automatic setting of default column widths AND user resizing or is there another technique I must use when populating the DataGridView control?

Answer Source

This trick works for me:

    grd.DataSource = DT

    'set autosize mode
    grd.Columns(0).AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
    grd.Columns(1).AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
    grd.Columns(2).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill

    'datagrid has calculated it's widths so we can store them
    For i = 0 To grd.Columns.Count - 1
        'store autosized widths
        Dim colw As Integer = grd.Columns(i).Width
        'remove autosizing
        grd.Columns(i).AutoSizeMode = DataGridViewAutoSizeColumnMode.None
        'set width to calculated by autosize
        grd.Columns(i).Width = colw

What happens here is that you set autosize to whathever mode you need and then column by column you store the width it got from autosize calculation, remove autosizing and set width to value you stored before.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download