Autofit Grid Columns

  • Thread starter Thread starter Sean
  • Start date Start date
S

Sean

Hello, I have created a Datagrid which is populated by my
program. I would like to add code to cause each column
to expand to fit its largest item. This is similar to
the autofit in Excel. Is there a good way to do this?

Thanks
Sean
 
One way to do this is to use MeasureString to compute the size of the text
in each cell, and then take the maximum value. Below is a code snippet that
does this. It assumes your datagrid is bound to a datatable.

public void AutoSizeCol(int col)

{

float width = 0;

int numRows = ((DataTable) dataGrid1.DataSource).Rows.Count;



Graphics g = Graphics.FromHwnd(dataGrid1.Handle);

StringFormat sf = new StringFormat(StringFormat.GenericTypographic);

SizeF size;



for(int i = 0; i < numRows; ++ i)

{

size = g.MeasureString(dataGrid1[i, col].ToString(),
dataGrid1.Font, 500, sf);

if(size.Width > width)

width = size.Width;

}



g.Dispose();



dataGrid1.TableStyles["customers"].GridColumnStyles[col].Width = (int)
width + 8; // 8 is for leading and trailing padding

}



http://www.syncfusion.com/FAQ/WinForms/FAQ_c44c.asp#q877q
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Datagrid Columns 3
Autofit Datagrid Columns 4
Autofit DataGrid Columns 1
Datagrid / Columns / Autofit 1
Currency autofit 5
Autofit/wraptext on vbLf problem 2
Autofit 1
AutoFit 4

Back
Top