How to Transpose DataTable in C# ?

In this article we are going to see, How to transpose DataTable in C#? It means we are going to convert DataRow into DataColumn and DataColumn intoDataRow.Following is the simple and self-explanatory example in the form of code comment.

Code Snippet:-

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BlogsProgram
{

public class TansposeDataTableClass
{

public void TransposeDataTable()
{
// Defined Table as "Employee".
DataTable dt = new DataTable("Employee");
// Defined "EmpID" column as Integer Datatype.
dt.Columns.Add("EmpID", typeof(Int32));
// Defined "EmpName" column as String Datatype.
dt.Columns.Add("EmpName", typeof(string));
// Defined "EmpRank" column as String Datatype.
dt.Columns.Add("Rank", typeof(string));
//Inserting Data into above-defined DataTable
dt.Rows.Add(1, "Raj", "Hyderabad"); // Adding Row 1 to Table
dt.Rows.Add(2, "Shubh", "Nagpur"); // Adding Row 2 to Table
dt.Rows.Add(3, "Neha", "Pune"); // Adding Row 3 to Table
DataTable inputTable = dt;
// Table shown in Figure 1.1
// Calling GenerateTransposedTable() with Datatable as inpute parameter
DataTable transposedTable = GenerateTransposedTable(inputTable);
// Now we got "transposedTable" Transpose table.
//We can use it to bind with grid or for any other operations.
}

private DataTable GenerateTransposedTable(DataTable inputTable)
{
DataTable outputTable = new DataTable();
// Add columns by looping rows
// Header row's first column is the same as in input Table
outputTable.Columns.Add(inputTable.Columns[0].ColumnName.ToString());
// Header row's second column onwards, 'inputTable's first column taken
foreach (DataRow inRow in inputTable.Rows)
{
string newColName = inRow[0].ToString();
outputTable.Columns.Add(newColName);
}
// Add rows by looping columns
for (int rCount = 1; rCount <= inputTable.Columns.Count - 1; rCount++)
{
DataRow newRow = outputTable.NewRow();
// First column is inputTable's Header row's second column
newRow[0] = inputTable.Columns[rCount].ColumnName.ToString();
for (int cCount = 0; cCount <= inputTable.Rows.Count - 1; cCount++)
{
string colValue = inputTable.Rows[cCount][rCount].ToString();
newRow[cCount + 1] = colValue;
}
outputTable.Rows.Add(newRow);
}
return outputTable;
}
}
}













Comments

Unknown said…
Very useful for me and easy to understand

Popular posts from this blog

Process Template Editor Extension Tool in Visual Studio Integration Tutorial

Docker’s Basic Tutorial

React Js Tutorial for beginner