In Gridex Janus, you can double-click a column header (actually the line between 2 column headers) and the column to the left will expand in width to fit the length of the longest text. Is there a way to get the longest text programmatically?
Asked
Active
Viewed 1,115 times
1
-
Yes, there is. You can use [TextRenderer.MeasureText](https://msdn.microsoft.com/en-us/library/system.windows.forms.textrenderer.measuretext(v=vs.110).aspx). But if your goal is making the column size larger programmatically, the control most likely have built-in support for auto-sized columns. – Reza Aghaei Oct 06 '16 at 10:31
1 Answers
0
If your goal is to resize all columns try using
GridEx.autosizeColumns()
if not try this linq code that returns max len for each column in a datatable (assuming at least one non-null value in each column, otherwise, Max will throw an exception)
List<int> maximumLengthForColumns =
Enumerable.Range(0, dataTable.Columns.Count)
.Select(col => dataTable.AsEnumerable()
.Select(row => row[col]).OfType<string>()
.Max(val => val.Length)).ToList();
or use this code to get maximum length in the whole table
int maxLength = dataTable.AsEnumerable()
.SelectMany(row => row.ItemArray.OfType<string>())
.Max(str => str.Length);

Hadi
- 36,233
- 13
- 65
- 124