When there is a need to have each column in a DataGridView to display the widest value the solution may be to iterate each column and set column .AutoSizeMode to AllCells.
Change the widest column value or any cell value passed the widest value and the DataGridView will adjust to the new value.
Using the above now means a user can not manually resize columns. This can be remedied while with the solution shown below auto-size is not possible unless using a loop done originally.
Can we poke the elephant at the code, sure, it's not going to fit all situations and a smart coder will see this and possibly modify the code or simply ignore the code.
To call the method, first set the DataGriView DataSource then use the extension method e.g.
Code:
DataGridView1.ExpandColumns ' columns can not be resized by the user
DataGridView1.ExpandColumns(True) ' columns can be resized by the user
Code:
Public Module DataGridViewExtensions
''' <summary>
''' Expand all columns and suitable for working with Entity Framework in regards to ICollection`1 column types.
''' </summary>
''' <param name="sender"></param>
''' <param name="sizable">Undue DataGridViewAutoSizeColumnMode.AllCells which makes manual resizing possible</param>
Public Sub ExpandColumns(sender As DataGridView, Optional sizable As Boolean = False)
For Each column As DataGridViewColumn In sender.Columns
If column.ValueType.Name <> "ICollection`1" Then
column.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
End If
Next
If Not sizable Then
Return
End If
For index As Integer = 0 To sender.Columns.Count - 1
Dim columnWidth As Integer = sender.Columns(index).Width
sender.Columns(index).AutoSizeMode = DataGridViewAutoSizeColumnMode.None
sender.Columns(index).Width = columnWidth
Next
End Sub
End Module