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?
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;
}
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:
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);
};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With