Link to home
Start Free TrialLog in
Avatar of preskh
preskh

asked on

Automatically resize datagrid column width

How to automatically resize a datgrid's column width to the length of the longest item in a column. How to apply it to this code ?

Dim dTable As New DataTable

dTable.Columns.Add("Name")
dTable.Columns.Add("Information")
Dim myDatatView As New DataView(dTable)
DataGrid1.DataSource = myDatatView

Dim dRow As DataRow

dRow = dTable.NewRow
dRow(0) = "aa"
dRow(1) = "bb"
dTable.Rows.Add(dRow)

dRow = dTable.NewRow
dRow(0) = "123aaaaaaaaaaaaaaaaaaaaa456"
dRow(1) = "123bbbbbbbb456"
dTable.Rows.Add(dRow)
SOLUTION
Avatar of 123654789987
123654789987

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Avatar of Éric Moreau
Éric Moreau
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of preskh
preskh

ASKER

I have already seen the microsoft article and some datagrid resizing questions in experts-exchange. But I am not sure how to apply that to this case where data in rows are manually added through code.

emoreau I converted the VB 6 code given in your link to VB .Net code and I get this error in the "numRows = CType(dataGrid1.DataSource, DataTable).Rows.Count" line

An unhandled exception of type 'System.InvalidCastException' occurred in WindowsApplication1.exe

Additional information: Specified cast is not valid.

Also should I change the 'customers' in the line "dataGrid1.TableStyles("customers").GridColumnStyles(col).Width = CType(width, Integer)" to 'Name'(Name and Information are the column headings in my code)
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>>emoreau I converted the VB 6 code given in your link to VB .Net code

It is surely not VB6! It is C#. You can download the VB.Net equivalent using the "VB" link at the end of the description.


>>and I get this error in the "numRows = CType(dataGrid1.DataSource, DataTable).Rows.Count" line
>>An unhandled exception of type 'System.InvalidCastException' occurred in WindowsApplication1.exe

What is your DataSource set to? If if is a DataView, then you have to cast it as a DataView instead of a DataTable.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial