How to: Automatically Resize Cells When Content Changes in the Windows Forms DataGridView Control

You can configure the DataGridView control to resize its rows, columns, and headers automatically whenever content changes, so that cells are always large enough to display their values without clipping.

You have many options to restrict which cells are used to determine the new sizes. For example, you can configure the control to automatically resize the width of its columns based only on the values in rows that are currently displayed. With this, you can avoid inefficiency when working with large numbers of rows, although in this case, you might want to use sizing methods such as AutoResizeColumns to adjust sizes at times of your choosing.

For more information about automatic resizing, see Sizing Options in the Windows Forms DataGridView Control.

The following code example demonstrates the options available for automatic resizing.

Example

Public Class AutoSizing
    Inherits System.Windows.Forms.Form

    Friend WithEvents FlowLayoutPanel1 As FlowLayoutPanel
    Friend WithEvents Button1 As Button = New Button()
    Friend WithEvents Button2 As Button = New Button()
    Friend WithEvents Button3 As Button = New Button()
    Friend WithEvents Button4 As Button = New Button()
    Friend WithEvents Button5 As Button = New Button()
    Friend WithEvents Button6 As Button = New Button()
    Friend WithEvents Button7 As Button = New Button()
    Friend WithEvents Button8 As Button = New Button()
    Friend WithEvents Button9 As Button = New Button()
    Friend WithEvents Button10 As Button = New Button()
    Friend WithEvents Button11 As Button = New Button()
    Friend WithEvents DataGridView1 As DataGridView

    Public Sub New()
        MyBase.New()
        InitializeComponent()
        AddDirections()

        AddButton(Button1, "Reset")
        AddButton(Button2, "Change Column 3 Header")
        AddButton(Button3, "Change Meatloaf Recipe")
        AddButton(Button4, "Change Restaurant 2")

        AddButtonsForAutomaticResizing()
    End Sub

    Private Sub AddDirections()
        Dim directions As New Label()
        directions.AutoSize = True
        Dim newLine As String = Environment.NewLine
        directions.Text = "Press the buttons that start " & newLine _
            & "with 'Change' to see how different sizing " & newLine _
            & "modes deal with content changes."

        FlowLayoutPanel1.Controls.Add(directions)
    End Sub

    Private Sub InitializeComponent()
        Me.FlowLayoutPanel1 = New FlowLayoutPanel
        Me.FlowLayoutPanel1.FlowDirection = FlowDirection.TopDown
        Me.FlowLayoutPanel1.Location = _
            New System.Drawing.Point(454, 0)
        Me.FlowLayoutPanel1.AutoSize = True
        Me.FlowLayoutPanel1.TabIndex = 7

        Me.Controls.Add(Me.FlowLayoutPanel1)
        Me.Text = Me.GetType().Name
        Me.AutoSize = True
    End Sub

    Private startingSize As Size
    Private thirdColumnHeader As String = "Main Ingredients"
    Private boringMeatloaf As String = "ground beef"
    Private boringMeatloafRanking As String = "*"
    Private boringRecipe As Boolean
    Private shortMode As Boolean
    Private otherRestaurant As String = "Gomes's Saharan Sushi"

    Private Sub InitializeDataGridView(ByVal ignored As Object, _
    ByVal ignoredToo As EventArgs) Handles Me.Load
        DataGridView1 = New System.Windows.Forms.DataGridView
        Controls.Add(DataGridView1)
        startingSize = New Size(450, 400)
        DataGridView1.Size = startingSize

        SetUpColumns()
        PopulateRows()

        shortMode = False
        boringRecipe = True
        AddLabels()
    End Sub

    Private Sub SetUpColumns()
        DataGridView1.ColumnCount = 4
        DataGridView1.ColumnHeadersVisible = True

        Dim columnHeaderStyle As New DataGridViewCellStyle
        columnHeaderStyle.BackColor = Color.Aqua
        columnHeaderStyle.Font = New Font("Verdana", 10, _
            FontStyle.Bold)
        DataGridView1.ColumnHeadersDefaultCellStyle = _
            columnHeaderStyle

        DataGridView1.Columns(0).Name = "Recipe"
        DataGridView1.Columns(1).Name = "Category"
        DataGridView1.Columns(2).Name = thirdColumnHeader
        DataGridView1.Columns(3).Name = "Rating"
    End Sub

    Private Sub PopulateRows()
        Dim row1 As String() = New String() _
            {"Meatloaf", "Main Dish", boringMeatloaf, _
            boringMeatloafRanking}
        Dim row2 As String() = New String() _
            {"Key Lime Pie", "Dessert", _
            "lime juice, evaporated milk", _
            "****"}
        Dim row3 As String() = New String() _
            {"Orange-Salsa Pork Chops", "Main Dish", _
            "pork chops, salsa, orange juice", "****"}
        Dim row4 As String() = New String() _
            {"Black Bean and Rice Salad", "Salad", _
            "black beans, brown rice", _
            "****"}
        Dim row5 As String() = New String() _
            {"Chocolate Cheesecake", "Dessert", "cream cheese", _
                "***"}
        Dim row6 As String() = New String() _
            {"Black Bean Dip", "Appetizer", "black beans, sour cream", _
                "***"}
        Dim rows As Object() = New Object() {row1, row2, row3, _
            row4, row5, row6}

        Dim rowArray As String()
        For Each rowArray In rows
            DataGridView1.Rows.Add(rowArray)
        Next

        For Each row As DataGridViewRow In DataGridView1.Rows
            If row.IsNewRow Then Continue For
            row.HeaderCell.Value = "Restaurant " & row.Index
        Next
    End Sub

    Private Sub AddButton(ByVal button As Button, _
        ByVal buttonLabel As String)

        button.Text = buttonLabel
        button.AutoSize = True
        FlowLayoutPanel1.Controls.Add(button)
    End Sub

    Private Sub resetToDisorder(ByVal sender As Object, _
        ByVal e As System.EventArgs) _
        Handles Button1.Click

        DataGridView1.Size = startingSize
        Controls.Remove(DataGridView1)
        DataGridView1.Dispose()
        InitializeDataGridView(Nothing, Nothing)
    End Sub

    Private Sub ChangeColumn3Header(ByVal sender As Object, _
        ByVal e As System.EventArgs) _
        Handles Button2.Click

        Toggle(shortMode)
        If shortMode Then DataGridView1.Columns(2).HeaderText = "S" _
            Else DataGridView1.Columns(2).HeaderText = _
                thirdColumnHeader
    End Sub

    Private Shared Function Toggle(ByRef toggleThis As Boolean) _
    As Boolean
        toggleThis = Not toggleThis
        Return toggleThis
    End Function

    Private Sub ChangeMeatloafRecipe(ByVal sender As Object, _
        ByVal e As System.EventArgs) _
        Handles Button3.Click

        Toggle(boringRecipe)
        If boringRecipe Then
            SetMeatloaf(boringMeatloaf, boringMeatloafRanking)
        Else
            Dim greatMeatloafRecipe As String = "1 lb. lean ground beef, " _
                & "1/2 cup bread crumbs, 1/4 cup ketchup," _
                & "1/3 tsp onion powder, " _
                & "1 clove of garlic, 1/2 pack onion soup mix, " _
                & "dash of your favorite BBQ Sauce"
            SetMeatloaf(greatMeatloafRecipe, "***")
        End If
    End Sub

    Private Sub ChangeRestaurant(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles Button4.Click

        If Not DataGridView1.Rows(2).HeaderCell.Value _
            .Equals(otherRestaurant) Then

            DataGridView1.Rows(2).HeaderCell.Value = _
                otherRestaurant
        Else
            DataGridView1.Rows(2).HeaderCell.Value = _
                "Restaurant 2"
        End If
    End Sub

    Private Sub SetMeatloaf(ByVal recipe As String, _
    ByVal rating As String)
        DataGridView1.Rows(0).Cells(2).Value = recipe
        DataGridView1.Rows(0).Cells(3).Value = rating
    End Sub

    Private currentLayoutName As String = _
        "DataGridView.AutoSizeRowsMode is currently: "
    Private Sub AddLabels()
        Dim current As Label = CType( _
        FlowLayoutPanel1.Controls(currentLayoutName), Label)

        If current Is Nothing Then
            current = New Label()
            current.AutoSize = True
            current.Name = currentLayoutName
            FlowLayoutPanel1.Controls.Add(current)
            current.Text = currentLayoutName & _
               DataGridView1.AutoSizeRowsMode.ToString()
        End If
    End Sub

#Region "Automatic Resizing"
    Private Sub AddButtonsForAutomaticResizing()
        AddButton(Button5, "Keep Column Headers Sized")
        AddButton(Button6, "Keep Row Headers Sized")
        AddButton(Button7, "Keep Rows Sized")
        AddButton(Button8, "Keep Row Headers Sized with RowsMode")
        AddButton(Button9, "Disable AutoSizeRowsMode")
        AddButton(Button10, "AutoSize third column by rows")
        AddButton(Button11, "AutoSize third column by rows and headers")
    End Sub

    Private Sub ColumnHeadersHeightSizeMode(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles Button5.Click

        DataGridView1.ColumnHeadersHeightSizeMode = _
            DataGridViewColumnHeadersHeightSizeMode.AutoSize

    End Sub

    Private Sub RowHeadersWidthSizeMode(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles Button6.Click

        DataGridView1.RowHeadersWidthSizeMode = _
            DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders

    End Sub

    Private Sub AutoSizeRowsMode(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles Button7.Click

        DataGridView1.AutoSizeRowsMode = _
            DataGridViewAutoSizeRowsMode.AllCells

    End Sub

    Private Sub AutoSizeRowHeadersUsingAllHeadersMode _
        (ByVal sender As Object, ByVal e As System.EventArgs) _
        Handles Button8.Click

        DataGridView1.AutoSizeRowsMode = _
            DataGridViewAutoSizeRowsMode.AllHeaders

    End Sub

    Private Sub WatchRowsModeChanges(ByVal sender As Object, _
        ByVal modeEvent As DataGridViewAutoSizeModeEventArgs) _
        Handles DataGridView1.AutoSizeRowsModeChanged

        Dim label As Label = CType(FlowLayoutPanel1.Controls _
            (currentLayoutName), Label)

        If modeEvent.PreviousModeAutoSized Then
            label.Text = "changed to different " & label.Name & _
                DataGridView1.AutoSizeRowsMode.ToString()
        Else
            label.Text = label.Name & _
                DataGridView1.AutoSizeRowsMode.ToString()
        End If
    End Sub

    Private Sub DisableAutoSizeRowsMode(ByVal sender As Object, _
    ByVal modeEvent As EventArgs) Handles Button9.Click

        DataGridView1.AutoSizeRowsMode = _
            DataGridViewAutoSizeRowsMode.None
    End Sub

    Private Sub AutoSizeOneColumn(ByVal sender As Object, _
    ByVal theEvent As EventArgs) Handles Button10.Click

        Dim column As DataGridViewColumn = DataGridView1.Columns(2)
        column.AutoSizeMode = _
            DataGridViewAutoSizeColumnMode.DisplayedCells

    End Sub

    Private Sub AutoSizeOneColumnIncludingHeaders(ByVal sender As Object, _
    ByVal theEvent As EventArgs) Handles Button11.Click

        Dim column As DataGridViewColumn = DataGridView1.Columns(2)
        column.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells

    End Sub
#End Region

    <STAThreadAttribute()> _
    Public Shared Sub Main()
        Application.Run(New AutoSizing())
    End Sub

End Class
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;

public class AutoSizing : System.Windows.Forms.Form
{
    private FlowLayoutPanel flowLayoutPanel1;
    private Button button1 = new Button();
    private Button button2 = new Button();
    private Button button3 = new Button();
    private Button button4 = new Button();
    private Button button5 = new Button();
    private Button button6 = new Button();
    private Button button7 = new Button();
    private Button button8 = new Button();
    private Button button9 = new Button();
    private Button button10 = new Button();
    private Button button11 = new Button();
    private DataGridView dataGridView1;

    public AutoSizing()
    {
        InitializeComponent();
        this.Load += new EventHandler(InitializeDataGridView);

        AddDirections();
        AddButton(button1, "Reset",
            new EventHandler(ResetToDisorder));
        AddButton(button2, "Change Column 3 Header",
            new EventHandler(ChangeColumn3Header));
        AddButton(button3, "Change Meatloaf Recipe",
            new EventHandler(ChangeMeatloafRecipe));
        AddButton(button4, "Change Restaurant 2",
            new EventHandler(ChangeRestaurant));
        AddButtonsForAutomaticResizing();
    }

    private void AddDirections()
    {
        Label directions = new Label();
        directions.AutoSize = true;
        String newLine = Environment.NewLine;
        directions.Text = "Press the buttons that start " + newLine
            + "with 'Change' to see how different sizing " + newLine
            + "modes deal with content changes.";

        flowLayoutPanel1.Controls.Add(directions);
    }

    private void InitializeComponent()
    {
        flowLayoutPanel1 = new FlowLayoutPanel();
        flowLayoutPanel1.FlowDirection = FlowDirection.TopDown;
        flowLayoutPanel1.Location = new System.Drawing.Point(492, 0);
        flowLayoutPanel1.AutoSize = true;
        flowLayoutPanel1.TabIndex = 1;

        ClientSize = new System.Drawing.Size(674, 419);
        Controls.Add(flowLayoutPanel1);
        Text = this.GetType().Name;
        AutoSize = true;
    }

    [STAThreadAttribute()]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.Run(new AutoSizing());
    }

    private Size startingSize;
    private string thirdColumnHeader = "Main Ingredients";
    private string boringMeatloaf = "ground beef";
    private string boringMeatloafRanking = "*";
    private bool boringRecipe;
    private bool shortMode;
    private string otherRestaurant = "Gomes's Saharan Sushi";

    private void InitializeDataGridView(Object ignored,
        EventArgs ignoredToo)
    {
        dataGridView1 = new System.Windows.Forms.DataGridView();
        Controls.Add(dataGridView1);
        startingSize = new Size(450, 400);
        dataGridView1.Size = startingSize;
        dataGridView1.AutoSizeRowsModeChanged +=
            new DataGridViewAutoSizeModeEventHandler
                (WatchRowsModeChanges);
        AddLabels();

        SetUpColumns();
        PopulateRows();

        shortMode = false;
        boringRecipe = true;
    }

    private void SetUpColumns()
    {
        dataGridView1.ColumnCount = 4;
        dataGridView1.ColumnHeadersVisible = true;

        DataGridViewCellStyle columnHeaderStyle =
            new DataGridViewCellStyle();

        columnHeaderStyle.BackColor = Color.Aqua;
        columnHeaderStyle.Font = new Font("Verdana", 10,
            FontStyle.Bold);
        dataGridView1.ColumnHeadersDefaultCellStyle =
            columnHeaderStyle;

        dataGridView1.Columns[0].Name = "Recipe";
        dataGridView1.Columns[1].Name = "Category";
        dataGridView1.Columns[2].Name = thirdColumnHeader;
        dataGridView1.Columns[3].Name = "Rating";
    }

    private void PopulateRows()
    {
        string[] row1 = {
            "Meatloaf", "Main Dish", boringMeatloaf, boringMeatloafRanking
        };
        string[] row2 = {
            "Key Lime Pie", "Dessert", "lime juice, evaporated milk", "****"
        };
        string[] row3 = {
            "Orange-Salsa Pork Chops", "Main Dish", 
            "pork chops, salsa, orange juice", "****"
        };
        string[] row4 = {
            "Black Bean and Rice Salad", "Salad", 
            "black beans, brown rice", "****"
        };
        string[] row5 = {
            "Chocolate Cheesecake", "Dessert", "cream cheese", "***"
        };
        string[] row6 = {
            "Black Bean Dip", "Appetizer", "black beans, sour cream", "***"
        };
        object[] rows = new object[] {
            row1, row2, row3, row4, row5, row6
        };

        foreach (string[] row in rows)
            dataGridView1.Rows.Add(row);

        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (row.IsNewRow) break;
            row.HeaderCell.Value = "Restaurant " + row.Index;
        }
    }

    private void AddButton(Button button, string buttonLabel,
        EventHandler handler)
    {
        button.Click += handler;
        button.Text = buttonLabel;
        button.AutoSize = true;
        button.TabIndex = flowLayoutPanel1.Controls.Count;
        flowLayoutPanel1.Controls.Add(button);
    }

    private void ResetToDisorder(Object sender, EventArgs e)
    {
        Controls.Remove(dataGridView1);
        dataGridView1.Dispose();
        InitializeDataGridView(null, null);
    }

    private void ChangeColumn3Header(Object sender, EventArgs e)
    {
        Toggle(ref shortMode);
        if (shortMode) dataGridView1.Columns[2].HeaderText = "S";
        else
            dataGridView1.Columns[2].HeaderText = thirdColumnHeader;
    }

    private static Boolean Toggle(ref Boolean toggleThis)
    {
        toggleThis = !toggleThis;
        return toggleThis;
    }

    private void ChangeMeatloafRecipe(Object sender, EventArgs e)
    {
        Toggle(ref boringRecipe);
        if (boringRecipe)
            SetMeatloaf(boringMeatloaf, boringMeatloafRanking);
        else
        {
            string greatMeatloafRecipe = "1 lb. lean ground beef, "
                + "1/2 cup bread crumbs, 1/4 cup ketchup,"
                + "1/3 tsp onion powder, "
                + "1 clove of garlic, 1/2 pack onion soup mix,"
                + " dash of your favorite BBQ Sauce";

            SetMeatloaf(greatMeatloafRecipe, "***");
        }
    }

    private void ChangeRestaurant(Object sender, EventArgs ignored)
    {
        if (dataGridView1.Rows[2].HeaderCell.Value.ToString() ==
            otherRestaurant)
            dataGridView1.Rows[2].HeaderCell.Value =
                "Restaurant 2";
        else
            dataGridView1.Rows[2].HeaderCell.Value =
            otherRestaurant;
    }

    private void SetMeatloaf(string recipe, string rating)
    {
        dataGridView1.Rows[0].Cells[2].Value = recipe;
        dataGridView1.Rows[0].Cells[3].Value = rating;
    }

    private string currentLayoutName =
        "DataGridView.AutoSizeRowsMode is currently: ";
    private void AddLabels()
    {
        Label current = (Label)
            flowLayoutPanel1.Controls[currentLayoutName];
        if (current == null)
        {
            current = new Label();
            current.AutoSize = true;
            current.Name = currentLayoutName;
            current.Text = currentLayoutName +
            dataGridView1.AutoSizeRowsMode.ToString();
            flowLayoutPanel1.Controls.Add(current);
        }
    }

    #region "Automatic Resizing"
    private void AddButtonsForAutomaticResizing()
    {
        AddButton(button5, "Keep Column Headers Sized",
            new EventHandler(ColumnHeadersHeightSizeMode));
        AddButton(button6, "Keep Row Headers Sized",
            new EventHandler(RowHeadersWidthSizeMode));
        AddButton(button7, "Keep Rows Sized",
            new EventHandler(AutoSizeRowsMode));
        AddButton(button8, "Keep Row Headers Sized with RowsMode",
            new EventHandler(AutoSizeRowHeadersUsingAllHeadersMode));
        AddButton(button9, "Disable AutoSizeRowsMode",
            new EventHandler(DisableAutoSizeRowsMode));
        AddButton(button10, "AutoSize third column by rows",
            new EventHandler(AutoSizeOneColumn));
        AddButton(button11, "AutoSize third column by rows and headers",
            new EventHandler(AutoSizeOneColumnIncludingHeaders));
    }

    private void ColumnHeadersHeightSizeMode(Object sender, EventArgs e)
    {
        dataGridView1.ColumnHeadersHeightSizeMode = 
            DataGridViewColumnHeadersHeightSizeMode.AutoSize;
    }

    private void RowHeadersWidthSizeMode(Object sender, EventArgs e)
    {
        dataGridView1.RowHeadersWidthSizeMode = 
            DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
    }

    private void AutoSizeRowsMode(Object sender, EventArgs es)
    {
        dataGridView1.AutoSizeRowsMode =
            DataGridViewAutoSizeRowsMode.AllCells;
    }

    private void AutoSizeRowHeadersUsingAllHeadersMode(
        Object sender, System.EventArgs e)
    {
        dataGridView1.AutoSizeRowsMode =
            DataGridViewAutoSizeRowsMode.AllHeaders;
    }

    private void WatchRowsModeChanges(object sender,
        DataGridViewAutoSizeModeEventArgs modeEvent)
    {
        Label label =
            (Label)flowLayoutPanel1.Controls[currentLayoutName];

        if (modeEvent.PreviousModeAutoSized)
        {
            label.Text = "changed to a different " +
                label.Name +
                dataGridView1.AutoSizeRowsMode.ToString();
        }
        else
        {
            label.Text = label.Name +
                dataGridView1.AutoSizeRowsMode.ToString();
        }
    }

    private void DisableAutoSizeRowsMode(object sender,
        EventArgs modeEvent)
    {
        dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
    }

    private void AutoSizeOneColumn(object sender,
        EventArgs theEvent)
    {
        DataGridViewColumn column = dataGridView1.Columns[2];
        column.AutoSizeMode = 
            DataGridViewAutoSizeColumnMode.DisplayedCellsExceptHeader;
    }

    private void AutoSizeOneColumnIncludingHeaders(
        object sender, EventArgs theEvent)
    {
        DataGridViewColumn column = dataGridView1.Columns[2];
        column.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
    }
    #endregion
}

Compiling the Code

This example requires:

  • References to the System, System.Drawing, and System.Windows.Forms assemblies.

For information about building this example from the command line for Visual Basic or Visual C#, see Building from the Command Line (Visual Basic) or Command-Line Building. You can also build this example in Visual Studio by pasting the code into a new project. How to: Compile and Run a Complete Windows Forms Code Example Using Visual Studio
How to: Compile and Run a Complete Windows Forms Code Example Using Visual Studio
How to: Compile and Run a Complete Windows Forms Code Example Using Visual Studio
How to: Compile and Run a Complete Windows Forms Code Example Using Visual Studio

See Also

Tasks

How to: Programmatically Resize Cells to Fit Content in the Windows Forms DataGridView Control

Reference

DataGridView
System.Windows.Forms.DataGridView.ColumnHeadersHeightSizeMode
System.Windows.Forms.DataGridView.RowHeadersWidthSizeMode
System.Windows.Forms.DataGridView.AutoSizeColumnsMode
System.Windows.Forms.DataGridView.AutoSizeRowsMode
System.Windows.Forms.DataGridViewColumn.AutoSizeMode
System.Windows.Forms.DataGridViewColumn.InheritedAutoSizeMode
DataGridViewAutoSizeRowsMode
DataGridViewAutoSizeColumnMode
DataGridViewAutoSizeColumnsMode
DataGridViewColumnHeadersHeightSizeMode
DataGridViewRowHeadersWidthSizeMode

Concepts

Sizing Options in the Windows Forms DataGridView Control

Other Resources

Resizing Columns and Rows in the Windows Forms DataGridView Control