Datagrid 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 easy way to do this?
 
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

}


SOURCE:
http://www.syncfusion.com/FAQ/WinForms/FAQ_c44c.asp#q877q
You can download complete examples here too!

--
Greetz

Jan Tielens
________________________________
Read my weblog: http://weblogs.asp.net/jan
 
Hi Sean,

I think a combination from something like this

AvgCharWidth =
CInt(Graphics.FromHwnd(Me.Handle).MeasureString("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
, Me.Font).Width / 26.0!)
tsl.GridColumnStyles.Item(0).Width = AvgCharWidth * MaxFoundedItemWidth

And something as this here for this message written (and never tested and
see it as a kind of pseudo)
\\\
dim mycolumnmax as array(numberofcolumns)
For i As Integer = 0 To MyTable.Columns.Count - 1
Dim max As Integer
max = 0
For y As Integer = 0 To MyTable.Rows.Count - 1
If MyTable.Rows(y).Item(i).ToString.Length > max Then
max = MyTable(0).Rows(y).Item(i).ToString.Length
End If
Next
mycolumnmax(i) = max
Next
///

Will maybe do what you ask, I am curious about that?

You have to do it everytime a user enters some data in your grid.

Cor
 
Hi Sean,

While doing this, I think suddenly, that it should be able to avoid that
most innerloop from the rows, by using a datatable.compute methode.

That is not one of my favorites, so when you want to use it you would have
to figured out yourself or have the luck that Jay B looks to it and does it
for you.

Cor
 
Back
Top