[c#] DataGridView AutoFit and Fill

I have 3 columns in my DataGridView. What I am trying to do is have the first 2 columns auto fit to the width of the content, and have the 3rd column fill the remaining space.

Is it possible to do in WinForms? I am loading my data from an EF DataContext if that's any use. I have included an image of how it currently looks.

enter image description here

This question is related to c# winforms datagridview

The answer is


This is what I have done in order to get the column "first_name" fill the space when all the columns cannot do it.

When the grid go to small the column "first_name" gets almost invisible (very thin) so I can set the DataGridViewAutoSizeColumnMode to AllCells as the others visible columns. For performance issues it´s important to set them to None before data binding it and set back to AllCell in the DataBindingComplete event handler of the grid. Hope it helps!

private void dataGridView1_Resize(object sender, EventArgs e)
    {
        int ColumnsWidth = 0;
        foreach(DataGridViewColumn col in dataGridView1.Columns)
        {
            if (col.Visible) ColumnsWidth += col.Width;
        }

        if (ColumnsWidth <dataGridView1.Width)
        {
            dataGridView1.Columns["first_name"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        }
        else if (dataGridView1.Columns["first_name"].Width < 10) dataGridView1.Columns["first_name"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
    }

This is my favorite approach...

_dataGrid.DataBindingComplete += (o, _) =>
    {
        var dataGridView = o as DataGridView;
        if (dataGridView != null)
        {
           dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
           dataGridView.Columns[dataGridView.ColumnCount-1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        }
    };

Try doing,

 AutoSizeColumnMode = Fill;

To build on AlfredBr's answer, if you hid some of your columns, you can use the following to auto-size all columns and then just have the last visible column fill the empty space:

myDgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
myDgv.Columns.GetLastColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.None).AutoSizeMode = 
    DataGridViewAutoSizeColumnMode.Fill;

Try this :

  DGV.AutoResizeColumns();
  DGV.AutoSizeColumnsMode=DataGridViewAutoSizeColumnsMode.AllCells;

public void setHeight(DataGridView src)
{
    src.Height= src.ColumnHeadersVisible ? src.ColumnHeadersHeight : 0 +   src.Rows.OfType<DataGridViewRow>().Where(row => row.Visible).Sum(row => row.Height);
}

Not tested but you can give a try. Tested and working. I hope you can play with AutoSizeMode of DataGridViewColum to achieve what you need.

Try setting

dataGridView1.DataSource = yourdatasource;<--set datasource before you set AutoSizeMode

//Set the following properties after setting datasource
dataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
dataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
dataGridView1.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

This should work


Just change Property from property of control: AutoSizeColumnsMode:Fill

OR By code

dataGridView1.AutoSizeColumnsMode=DataGridViewAutoSizeColumnsMode.Fill;


public static void Fill(DataGridView dgv2)
   {
        try
        {
            dgv = dgv2;
            foreach (DataGridViewColumn GridCol in dgv.Columns)
            {
                for (int j = 0; j < GridCol.DataGridView.ColumnCount; j++)
                {
                    GridCol.DataGridView.Columns[j].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                    GridCol.DataGridView.Columns[j].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                    GridCol.DataGridView.Columns[j].FillWeight = 1;
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to winforms

How to set combobox default value? Get the cell value of a GridView row Getting the first and last day of a month, using a given DateTime object Check if a record exists in the database Delete a row in DataGridView Control in VB.NET How to make picturebox transparent? Set default format of datetimepicker as dd-MM-yyyy Changing datagridview cell color based on condition C# Inserting Data from a form into an access Database How to use ConfigurationManager

Examples related to datagridview

How to refresh or show immediately in datagridview after inserting? Delete a row in DataGridView Control in VB.NET Looping each row in datagridview How to get cell value from DataGridView in VB.Net? Changing datagridview cell color based on condition Index was out of range. Must be non-negative and less than the size of the collection parameter name:index how to bind datatable to datagridview in c# DataGridView AutoFit and Fill How to export dataGridView data Instantly to Excel on button click? Populate a datagridview with sql query results