Transpose DataTable (swap rows with columns)

Data.DataTable NewTable = TransposeTable(OldTable);
private Data.DataTable TransposeTable(Data.DataTable InputTable)
{
 Data.DataTable OutputTable = new Data.DataTable();
 OutputTable.Columns.Add(InputTable.Columns(0).ColumnName);
 foreach (Data.DataRow InputRow in InputTable.Rows) {
  string NewColumnName = InputRow.Item(0);
  OutputTable.Columns.Add(NewColumnName);
 }
 for (int RowCount = 1; RowCount <= InputTable.Columns.Count - 1; RowCount++) {
  Data.DataRow NewRow = OutputTable.NewRow;
  NewRow.Item(0) = InputTable.Columns(RowCount).ColumnName;
  for (int ColumnCount = 0; ColumnCount <= InputTable.Rows.Count - 1; ColumnCount++) {
   string ColumnValue = InputTable.Rows(ColumnCount)(RowCount);
   NewRow(ColumnCount + 1) = ColumnValue;
  }
  OutputTable.Rows.Add(NewRow);
 }
 return OutputTable;
}

No comments:

Post a Comment