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

You can use the DataGridView control methods to resize rows, columns, and headers so that they display their entire values without truncation. You can use these methods to resize DataGridView elements at times of your choosing. Alternately, you can configure the control to resize these elements automatically whenever content changes. This can be inefficient, however, when you are working with large data sets or when your data changes frequently. For more information, see Sizing Options in the Windows Forms DataGridView Control.

Typically, you will programmatically adjust DataGridView elements to fit their content only when you load new data from a data source or when the user has edited a value. This is useful to optimize performance, but it is also useful when you want to enable your users to manually resize rows and columns with the mouse.

The following code example demonstrates the options available to you for programmatic resizing.


#using <System.Windows.Forms.dll>
#using <System.dll>
#using <System.Drawing.dll>

using namespace System;
using namespace System::Drawing;
using namespace System::Collections;
using namespace System::ComponentModel;
using namespace System::Windows::Forms;
public ref class ProgrammaticSizing: public System::Windows::Forms::Form
   FlowLayoutPanel^ flowLayoutPanel1;
   Button^ button1;
   Button^ button2;
   Button^ button3;
   Button^ button4;
   Button^ button5;
   Button^ button6;
   Button^ button7;
   Button^ button8;
   Button^ button9;
   Button^ button10;
   Button^ button11;

      button1 = gcnew Button;
      button2 = gcnew Button;
      button3 = gcnew Button;
      button4 = gcnew Button;
      button5 = gcnew Button;
      button6 = gcnew Button;
      button7 = gcnew Button;
      button8 = gcnew Button;
      button9 = gcnew Button;
      button10 = gcnew Button;
      button11 = gcnew Button;
      thirdColumnHeader = "Main Ingredients";
      boringMeatloaf = "ground beef";
      boringMeatloafRanking = "*";
      otherResturant = "Gomes's Saharan Sushi";
      this->Load += gcnew EventHandler( this, &ProgrammaticSizing::InitializeDataGridView );
      AddButton( button1, "Reset", gcnew EventHandler( this, &ProgrammaticSizing::ResetToDisorder ) );
      AddButton( button2, "Change Column 3 Header", gcnew EventHandler( this, &ProgrammaticSizing::ChangeColumn3Header ) );
      AddButton( button3, "Change Meatloaf Recipe", gcnew EventHandler( this, &ProgrammaticSizing::ChangeMeatloafRecipe ) );
      AddButton( button10, "Change Resturant 2", gcnew EventHandler( this, &ProgrammaticSizing::ChangeResturant ) );

   void InitializeComponent()
      this->flowLayoutPanel1 = gcnew FlowLayoutPanel;
      this->flowLayoutPanel1->FlowDirection = FlowDirection::TopDown;
      this->flowLayoutPanel1->Location = Point(492,0);
      this->flowLayoutPanel1->AutoSize = true;
      this->AutoSize = true;
      this->Controls->Add( this->flowLayoutPanel1 );
      this->Text = this->GetType()->Name;

   void AddDirections()
      Label^ directions = gcnew Label;
      directions->AutoSize = true;
      String^ newLine = Environment::NewLine;
      directions->Text = String::Format( "Press the buttons that start {0}with 'Change' to see how different sizing {1}modes deal with content changes.", newLine, newLine );
      flowLayoutPanel1->Controls->Add( directions );

   System::Drawing::Size startingSize;
   String^ thirdColumnHeader;
   String^ boringMeatloaf;
   String^ boringMeatloafRanking;
   bool boringRecipe;
   bool shortMode;
   DataGridView^ dataGridView1;
   String^ otherResturant;
   void InitializeDataGridView( Object^ /*sender*/, EventArgs^ /*ignoredToo*/ )
      this->dataGridView1 = gcnew DataGridView;
      this->dataGridView1->Location = Point(0,0);
      this->dataGridView1->Size = System::Drawing::Size( 292, 266 );
      this->Controls->Add( this->dataGridView1 );
      startingSize = System::Drawing::Size( 450, 400 );
      dataGridView1->Size = startingSize;
      shortMode = false;
      boringRecipe = true;

   void AddColumns()
      dataGridView1->ColumnCount = 4;
      dataGridView1->ColumnHeadersVisible = true;
      DataGridViewCellStyle ^ columnHeaderStyle = gcnew DataGridViewCellStyle;
      columnHeaderStyle->BackColor = Color::Aqua;
      columnHeaderStyle->Font = gcnew System::Drawing::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";

   void PopulateRows()
      array<String^>^row1 = {"Meatloaf","Main Dish",boringMeatloaf,boringMeatloafRanking};
      array<String^>^row2 = {"Key Lime Pie","Dessert","lime juice, evaporated milk","****"};
      array<String^>^row3 = {"Orange-Salsa Pork Chops","Main Dish","pork chops, salsa, orange juice","****"};
      array<String^>^row4 = {"Black Bean and Rice Salad","Salad","black beans, brown rice","****"};
      array<String^>^row5 = {"Chocolate Cheesecake","Dessert","cream cheese","***"};
      array<String^>^row6 = {"Black Bean Dip","Appetizer","black beans, sour cream","***"};
      array<Object^>^rows = {row1,row2,row3,row4,row5,row6};
      IEnumerator^ myEnum = rows->GetEnumerator();
      while ( myEnum->MoveNext() )
         array<String^>^row = safe_cast<array<String^>^>(myEnum->Current);
         dataGridView1->Rows->Add( row );

      IEnumerator^ myEnum1 = safe_cast<IEnumerable^>(dataGridView1->Rows)->GetEnumerator();
      while ( myEnum1->MoveNext() )
         DataGridViewRow ^ row = safe_cast<DataGridViewRow ^>(myEnum1->Current);
         if ( row->IsNewRow )
         row->HeaderCell->Value = String::Format( "Resturant {0}", row->Index );

   void AddButton( Button^ button, String^ buttonLabel, EventHandler^ handler )
      button->Text = buttonLabel;
      button->AutoSize = true;
      flowLayoutPanel1->Controls->Add( button );
      button->Click += handler;

   void ResetToDisorder( Object^ /*sender*/, EventArgs^ /*e*/ )
      Controls->Remove( dataGridView1 );
      dataGridView1->Size = startingSize;
      InitializeDataGridView( nullptr, nullptr );

   void ChangeColumn3Header( Object^ /*sender*/, EventArgs^ /*e*/ )
      Toggle(  &shortMode );
      if ( shortMode )
            dataGridView1->Columns[ 2 ]->HeaderText = "S";
            dataGridView1->Columns[ 2 ]->HeaderText = thirdColumnHeader;

   void Toggle( interior_ptr<Boolean> toggleThis )
       *toggleThis =  ! *toggleThis;

   void ChangeMeatloafRecipe( Object^ /*sender*/, EventArgs^ /*e*/ )
      Toggle(  &boringRecipe );
      if ( boringRecipe )
            SetMeatloaf( boringMeatloaf, boringMeatloafRanking );
         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, "***" );

   void SetMeatloaf( String^ recipe, String^ rating )
      dataGridView1->Rows[ 0 ]->Cells[ 2 ]->Value = recipe;
      dataGridView1->Rows[ 0 ]->Cells[ 3 ]->Value = rating;

   void ChangeResturant( Object^ /*sender*/, EventArgs^ /*ignored*/ )
      if ( dataGridView1->Rows[ 2 ]->HeaderCell->Value == otherResturant )
            dataGridView1->Rows[ 2 ]->HeaderCell->Value = "Resturant 2";
            dataGridView1->Rows[ 2 ]->HeaderCell->Value = otherResturant;

   void AddButtonsForProgrammaticResizing()
      AddButton( button4, "Size Third Column", gcnew EventHandler( this, &ProgrammaticSizing::SizeThirdColumnHeader ) );
      AddButton( button5, "Size Column Headers", gcnew EventHandler( this, &ProgrammaticSizing::SizeColumnHeaders ) );
      AddButton( button6, "Size All Columns", gcnew EventHandler( this, &ProgrammaticSizing::SizeAllColumns ) );
      AddButton( button7, "Size Third Row", gcnew EventHandler( this, &ProgrammaticSizing::SizeThirdRow ) );
      AddButton( button8, "Size First Row Header Using All Headers", gcnew EventHandler( this, &ProgrammaticSizing::SizeFirstRowHeaderToAllHeaders ) );
      AddButton( button9, "Size All Rows and Row Headers", gcnew EventHandler( this, &ProgrammaticSizing::SizeAllRowsAndTheirHeaders ) );
      AddButton( button11, "Size All Rows ", gcnew EventHandler( this, &ProgrammaticSizing::SizeAllRows ) );

   void SizeThirdColumnHeader( Object^ /*sender*/, EventArgs^ /*e*/ )
      dataGridView1->AutoResizeColumn(2, DataGridViewAutoSizeColumnMode::ColumnHeader);

   void SizeColumnHeaders( Object^ /*sender*/, EventArgs^ /*e*/ )
      int columnNumber;
      bool dontChangeColumnWidth;
      bool dontChangeRowHeadersWidth;

   void SizeAllColumns( Object^ /*sender*/, EventArgs^ /*e*/ )
      dataGridView1->AutoResizeColumns( DataGridViewAutoSizeColumnsMode::AllCells );

   void SizeThirdRow( Object^ /*sender*/, EventArgs^ /*e*/ )
      dataGridView1->AutoResizeRow(2, DataGridViewAutoSizeRowMode::AllCellsExceptHeader);

   void SizeFirstRowHeaderToAllHeaders( Object^ /*sender*/, EventArgs^ /*e*/ )
      dataGridView1->AutoResizeRowHeadersWidth(0, DataGridViewRowHeadersWidthSizeMode::AutoSizeToAllHeaders);

   void SizeAllRowsAndTheirHeaders( Object^ /*sender*/, EventArgs^ /*e*/ )

   void SizeAllRows( Object^ /*sender*/, EventArgs^ /*e*/ )


int main()
   Application::Run( gcnew ProgrammaticSizing );

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

public class ProgrammaticSizing : 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();

    public ProgrammaticSizing()
        this.Load += new EventHandler(InitializeDataGridView);

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

    #region form code
    private void InitializeComponent()
        this.flowLayoutPanel1 = new FlowLayoutPanel();
            = FlowDirection.TopDown;
        this.flowLayoutPanel1.Location = new Point(492, 0);
        this.flowLayoutPanel1.AutoSize = true;

        this.AutoSize = true;
        this.Text = this.GetType().Name;

    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.";


    static void Main()
        Application.Run(new ProgrammaticSizing());

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

    private void InitializeDataGridView(Object sender,
        EventArgs ignoredToo)
        this.dataGridView1 = new DataGridView();
        this.dataGridView1.Location = new Point(0, 0);
        this.dataGridView1.Size = new Size(292, 266);
        startingSize = new Size(450, 400);
        dataGridView1.Size = startingSize;


        shortMode = false;
        boringRecipe = true;

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

        DataGridViewCellStyle columnHeaderStyle =
            new DataGridViewCellStyle();

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

        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)
        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.Text = buttonLabel;
        button.AutoSize = true;
        button.Click += handler;

    private void ResetToDisorder(Object sender, EventArgs e)
        dataGridView1.Size = startingSize;
        InitializeDataGridView(null, null);

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

    private static void Toggle(ref Boolean toggleThis)
        toggleThis = !toggleThis;

    private void ChangeMeatloafRecipe(Object sender,
        EventArgs e)
        Toggle(ref boringRecipe);

        if (boringRecipe)
            SetMeatloaf(boringMeatloaf, boringMeatloafRanking);
            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 SetMeatloaf(string recipe, string rating)
        dataGridView1.Rows[0].Cells[2].Value = recipe;
        dataGridView1.Rows[0].Cells[3].Value = rating;

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

    #region "programmatic resizing"

    private void AddButtonsForProgrammaticResizing()
        AddButton(button4, "Size Third Column",
            new EventHandler(SizeThirdColumnHeader));
        AddButton(button5, "Size Column Headers",
            new EventHandler(SizeColumnHeaders));
        AddButton(button6, "Size All Columns",
            new EventHandler(SizeAllColumns));
        AddButton(button7, "Size Third Row",
            new EventHandler(SizeThirdRow));
        AddButton(button8, "Size First Row Header Using All Headers",
            new EventHandler(SizeFirstRowHeaderToAllHeaders));
        AddButton(button9, "Size All Rows and Row Headers",
            new EventHandler(SizeAllRowsAndTheirHeaders));
        AddButton(button11, "Size All Rows ",
            new EventHandler(SizeAllRows));

    private void SizeThirdColumnHeader(Object sender,
        EventArgs e)
            2, DataGridViewAutoSizeColumnMode.ColumnHeader);

    private void SizeColumnHeaders(Object sender, EventArgs e)

    private void SizeAllColumns(Object sender, EventArgs e)

    private void SizeThirdRow(Object sender, EventArgs e)
            2, DataGridViewAutoSizeRowMode.AllCellsExceptHeader);

    private void SizeFirstRowHeaderToAllHeaders(Object sender, EventArgs e)
            0, DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);

    private void SizeAllRowsAndTheirHeaders(Object sender, EventArgs e)

    private void SizeAllRows(Object sender,
        EventArgs e)
Public Class ProgrammaticSizing
    Inherits System.Windows.Forms.Form

#Region " form setup "
    Public Sub New()

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

    Friend WithEvents DataGridView1 As DataGridView
    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 FlowLayoutPanel1 As FlowLayoutPanel
    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()

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

        Me.AutoSize = True
        Me.Text = Me.GetType().Name
    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."

    End Sub

    Public Shared Sub Main()
        Application.Run(New ProgrammaticSizing())
    End Sub
#End Region

    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
        Me.DataGridView1 = New System.Windows.Forms.DataGridView
        Me.DataGridView1.Name = "DataGridView1"
        Me.DataGridView1.Size = New System.Drawing.Size(292, 266)

        startingSize = New Size(450, 400)
        DataGridView1.Size = startingSize


        shortMode = False
        boringRecipe = True
    End Sub

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

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

        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, _
        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

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

    End Sub

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

        button.Text = buttonLabel
        button.AutoSize = True
        button.TabIndex = FlowLayoutPanel1.Controls.Count
    End Sub

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

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

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

        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
    End Function

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

        If boringRecipe Then
            SetMeatloaf(boringMeatloaf, boringMeatloafRanking)

            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 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 Sub ChangeRestaurant(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles Button10.Click

        If DataGridView1.Rows(2).HeaderCell.Value.Equals(otherRestaurant) Then
            DataGridView1.Rows(2).HeaderCell.Value = _
                "Restaurant 2"
            DataGridView1.Rows(2).HeaderCell.Value = _
        End If

    End Sub

#Region "programmatic resizing"

    Private Sub AddButtonsForProgrammaticResizing()
        AddButton(Button4, "Size Third Column")
        AddButton(Button5, "Size Column Headers")
        AddButton(Button6, "Size All Columns")
        AddButton(Button7, "Size Third Row")
        AddButton(Button8, "Size First Row Header Using All Headers")
        AddButton(Button9, "Size All Rows and Row Headers")
        AddButton(Button11, "Size All Rows")
    End Sub

    ' The following code example resizes the second column to fit.
    Private Sub SizeThirdColumnHeader(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles Button4.Click

        DataGridView1.AutoResizeColumn( _
            2, DataGridViewAutoSizeColumnMode.ColumnHeader)

    End Sub

    ' The following code example resizes the second column to fit 
    ' the header 
    ' text, but it leaves the widths of the 
    ' row headers and columns unchanged.  
    Private Sub SizeColumnHeaders(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles Button5.Click


    End Sub

    ' The following code example resizes all the columns to fit the
    ' header text and column contents.  
    Private Sub SizeAllColumns(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles Button6.Click


    End Sub

    ' The following code example resizes the third row 
    ' to fit the column contents.   
    Private Sub SizeThirdRow(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles Button7.Click

        Dim thirdRow As Integer = 2
        DataGridView1.AutoResizeRow( _
            2, DataGridViewAutoSizeRowMode.AllCellsExceptHeader)

    End Sub

    ' The following code example resizes the first displayed row 
    ' to fit it's header. 
    Private Sub SizeFirstRowHeaderToAllHeaders(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles Button8.Click

        DataGridView1.AutoResizeRowHeadersWidth( _

    End Sub

    ' Size all the rows, including their headers and columns.
    Private Sub SizeAllRowsAndTheirHeaders(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles Button9.Click


    End Sub

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


    End Sub
#End Region
End Class

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 or Command-line Building With csc.exe. You can also build this example in Visual Studio by pasting the code into a new project. Also see How to: Compile and Run a Complete Windows Forms Code Example Using Visual Studio.

See Also

Resizing Columns and Rows in the Windows Forms DataGridView Control
Sizing Options in the Windows Forms DataGridView Control
How to: Automatically Resize Cells When Content Changes in the Windows Forms DataGridView Control