genespos genespos - 5 months ago 46
Vb.net Question

Get the max length for each field of a DataTable in VB.Net (Needed C# translation)

My goal is to show the whole content of a

DataTable
into a
RichTextBox
so I thought about using
String.Format
to make columns but I need to know the max length of contents for each Column.

I found the below C code on SO but I was unable to translate it to VB.Net:

List<int> maximumLengthForColumns =
Enumerable.Range(0, dataTable.Columns.Count)
.Select(col => dataTable.AsEnumerable()
.Select(row => row[col]).OfType<string>()
.Max(val => val.Length)).ToList();


Any hint on any different (and easier or better) way to reach my goal is appreciated.

SSS SSS
Answer
'dtb is the datatable'
Dim lstMaxLen As New List(Of Integer)
For Each dcl As DataColumn In dtb.Columns
  Dim intMaxLen As Integer = 0
  For Each drw As DataRow In dtb.Rows
    If drw(dcl.ColumnName).ToString.Length > intMaxLen Then
      intMaxLen = drw(dcl.ColumnName).ToString.Length
    End If
  Next drw
  lstMaxLen.Add(intMaxLen)
Next dcl
Comments