Search code examples
c#vb.netwinformsdatagridviewdatagridviewcombobox

How can I get a column in a DataGridView to autosize to the contents of a Combobox?


I have a column in a DataGridView with the column type DataGridViewComboBoxColumn . In this combo box, I have several strings of varying length. Some of these strings can be changed by the users in the application settings. It looks something like this:

screenshot of column

The column AutoSize options, such as AllCells, work nicely with DataGridViewTextBoxColumns. But they don't work as expected with combo boxes.

How can I set the width of this column to fit the contents of a combo box?


Solution

  • You can calculate width of items using TextRenderer.MeasureText and set the width of column to maximum value of the items width.

    To change width of column use Width property of column. To change only width of dropdown menu, use DropDownWidth property.

    // I suppose your column is at index 0
    var c = this.dataGridView1.Columns[0] as DataGridViewComboBoxColumn;
    c.Width = c.Items.Cast<Object>().Select(x => x.ToString())
        .Max(x => TextRenderer.MeasureText(x, c.InheritedStyle.Font,
            Size.Empty, TextFormatFlags.Default).Width);
    

    You can put above code in Load event handler of your form or in other places which you may want to reset the size of column.

    Note: In above example items of combobox are supposed to be of type of string. But you can use any type of items and extract text of items. The key point here is using TextRenderer.MeasureText with that parameters.

    VB Version

    Dim c = DirectCast(Me.DataGridView1.Columns(0), DataGridViewComboBoxColumn)
    c.Width = c.Items.Cast(Of Object)().Select(Function(x) x.ToString()) _
                .Max(Function(x) TextRenderer.MeasureText(x, c.InheritedStyle.Font, _
                    Size.Empty, TextFormatFlags.Default).Width)