Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGridView AutoSize

Tags:

.net

winforms

Is there any way to make DataGridView fit the width and height of colums/rows? I have found the solution which requires manual calulation: http://www.codeguru.com/csharp/.net/net_data/datagrid/article.php/c9603 Does DataGridView really not support this feature?

like image 979
SiberianGuy Avatar asked Jun 21 '11 11:06

SiberianGuy


2 Answers

if you want to make all the columns to resize automatically according to data:

for (int i = 0; i < dataGridView.Columns.Count; i++)
{
    dataGridView.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
}
like image 177
love Computer science Avatar answered Oct 03 '22 14:10

love Computer science


This is a pretty old question that has been misunderstood IMHO. What Idsa wants to achieve is to make the actual AutoSize winforms feature to work with the DataGridView. The property exists but it has no effect.

This means the DataGridView has to fit around its content, not its content has to fit inside the DataGridView.

There are a lot of things to think about to achieve a AutoSize implementation. The DataGridView size depends on a lot of criterias:

  • Border size
  • Padding
  • Cell Delimiter size
  • Row Header height
  • Column header width
  • How the DataGridView is populated (DataBound or manually)
  • ... a lot more

The best is to select a set of some criteria that fits your specific scenario, and write something that will compute the DataGridView size for you.

Here my specific scenario as an example:

  • my grid is data bound. So its size is supposed to change each time a DataBinding operation is complete. This is the condition that trigger a recalculation of the DataGridView size. So I hook it to the DataBindingComplete event.

  • my grid is not supposed to display scrollbars. So I set the Scrollbars property to None.

  • My row and columns autosize mode are set to AllCells.

  • Rows and Columns header are not visible. If they were, their sizes has to be included in the calculation.

The extension below method fits my needs. It is very simple because my grids are very simple. You will probably have to tweak it a bit to make it work as you wish, and a lot to make it work for every DataGridView scenarios.

public static void HandleAutoSize(this DataGridView dgv)
{
    dgv.DataBindingComplete += (s, e) =>
    {
        var dg = (DataGridView)s;
        var width = dg.Columns.GetColumnsWidth(DataGridViewElementStates.None);
        var height = dg.Rows.GetRowsHeight(DataGridViewElementStates.None);

        dg.ClientSize = new Size(width, height);
    };
}
like image 36
Larry Avatar answered Oct 03 '22 13:10

Larry