Transpose Data Table in .Net
Many times while developing code we come to the point when we need to convert columns of table into rows and vice-verso. Transpose of DataTable in .net is very simple we just need to use following function, which creates one table named outputDataTable this table has been created with reference to inputDataTable.
Though Transpose of Datatable in .net is easy task we need to understand that datatable is reference type, so we need make sure, one table is been transpose we dispose it after use or not.
private DataTable GenerateTransposedTable(DataTable inputDataTable) { DataTable outputDataTable = new DataTable(); // First column will remain the same outputDataTable.Columns.Add(inputDataTable.Columns[0].ColumnName.ToString()); // Creating Columns form each corresponding rows foreach (DataRow inputRow in inputDataTable.Rows) { string newColName = inputRow[0].ToString(); outputDataTable.Columns.Add(newColName); } // Add rows for (int rowCount = 1; rowCount <= inputDataTable.Columns.Count - 1; rowCount++) { DataRow newRow = outputDataTable.NewRow(); newRow[0] = inputDataTable.Columns[rowCount].ColumnName.ToString(); for (int coulmnCount = 0; coulmnCount <= inputDataTable.Rows.Count - 1; coulmnCount++) { string columnValue = inputDataTable.Rows[coulmnCount][rowCount].ToString(); newRow[coulmnCount + 1] = columnValue; } outputDataTable.Rows.Add(newRow); } return outputDataTable; }
0 comments:
Post a Comment