I have a function that builds a data table in VB.Net
Public Function GetDataTableFromSqlDataReader(ByVal dr As SqlDataReader) As DataTable
Dim dtSchema As DataTable = dr.GetSchemaTable()
Dim dt As New DataTable
Dim listCols As New ArrayList
If Not dtSchema Is Nothing Then
For Each drow As DataRow In dtSchema.Rows
Dim columnName As String = System.Convert.ToString(drow("ColumnName"))
Dim column As New DataColumn(columnName, DirectCast(drow("DataType"), Type))
column.Unique = CBool(drow("IsUnique"))
column.AllowDBNull = CBool(drow("AllowDBNull"))
column.AutoIncrement = CBool(drow("IsAutoIncrement"))
listCols.Add(column)
dt.Columns.Add(column)
Next
End If
While dr.Read()
Dim dataRow As DataRow = dt.NewRow()
For i As Integer = 0 To listCols.Count - 1
dataRow(DirectCast(listCols(i), DataColumn)) = dr(i)
Next
dt.Rows.Add(dataRow)
End While
Return dt
End Function
I'm returning a set of data with columns (UserName, TeamID, 10/1/2014, 10/2/2014, ..... 10/29/2014) and about 15 rows of data.
When the data reader builds the data table and adds the columns, instead of them being in the order above, they go UserName, TeamID, 10/14/2014, 10/8/2014, 10/20/2014.... with no discernible pattern.
I've verified that the SQL dataset is correct, and that when the datatable is being built is where the issue occurs.
Any ideas as to why this is happening, or what other things I should be looking it? This code works fine in all other cases, but this one time it's not adding the columns in the correct order.
EDIT:
If it makes a difference, the SQL I'm using is taking username, teamid, a count of items, and the date and putting them into a temporary table. I'm them pivoting the data to get a list of names/teamid's and the counts for each day in a single row. #P is just a list of the dates, #M holds the data being returned.
insert into #P(PV)
select DISTINCT ReportDate
FROM #M;
select @Pivot = coalesce(@Pivot+',','')+'['+PV+']'from #P;
SET @SQL = 'select * from (select UserName,TeamID,ReportDate,PropertyValue from #M) StdP PIVOT (SUM(PropertyValue) FOR ReportDate IN ('+@Pivot+')) as PVT order by TeamID, UserName'
EXEC(@SQL)
This is the order returned by my SQL query:
This is the order that the VB.Net datareader gives me..