I am trying to reorder the columns in a DataTable
by passing the DataTable
and a Dictionary
of options into a function, similar to as described in the answer to this thread.
Here is the code I am using:
Private Function ReorderColumns(dt As DataTable, options As Dictionary(Of String, Object)) As DataTable Dim orderList = New System.Collections.Generic.Dictionary(Of String, String) For Each item In options orderList.Add(item.Key, GetOptionValue(options(item.Key), "Order", Int32.MaxValue).ToString()) Next 'May be some untested regex characters that need to be added. For Each item In orderList.ToList() If String.IsNullOrEmpty(item.Value) Or Not IsNumeric(item.Value) Or Regex.IsMatch(item.Value, "[$.,]") Then orderList(item.Key) = Int32.MaxValue.ToString() End If Next Dim colOrd = orderList.OrderBy(Function(x) Convert.ToInt32(x.Value)).ToList() For Each lkey In colOrd For i As Integer = 0 To dt.Columns.Count - 1 If dt.Columns(i).ColumnName.Equals(lkey.Key) Then dt.Columns(i).SetOrdinal(lkey.Value - 1) Exit For End If Next Next Return dt End Function
The reordering takes place as desired. The issue is, there is no data in some of the columns when the DataTable
is returned.
I think I'm pretty close since the columns are reordering properly. It feels like the issue might be in this line:
dt.Columns(i).SetOrdinal(lkey.Value - 1)
The columns need to be able to be reordered for a MS Word report. The DataTable
is sent through a process that builds the report through OpenXML
. In fact, most of the required data shows up when the document is built. It's only on the rows where cells have been merged that the ColumnTitle no longer appears(it used to traverse the entire document, now it is blank instead).
The existing code was generating the report from the DataTable
just fine . So I'm trying to just reorder the columns before sending the DataTable
through it's usual processes.