Introduction

In this article I will describe how to display GridView columns as rows. The purpose is to just flip the data table which is used as a source for the GridView.

Step 1 : Create a web application and add 2 GridViews as below.

Code

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

<asp:Label runat="server" ID="ColumnsAsColumns" Text="Columns As Columns" />

<asp:GridView runat="server" ID="gvColumnsAsColumns" />

<asp:Label runat="server" ID="ColumnsAsRows" Text="Columns As Rows" />

<asp:GridView runat="server" ID="gvColumnsAsRows" />

</asp:Content>

Step 2 : In the page load event of the page, create a new DataTable. We can also fill a DataTable from the database. Since I don't need a database for demo purposes, I created my own DataTable.

Code

protected void Page_Load(object sender, EventArgs e)

{

//create new data table

DataTable dt = new DataTable();

//add columns to datatable

dt.Columns.Add("StudentID");

dt.Columns.Add("StudentName");

//create new row and add rows to datatable

DataRow dr = dt.NewRow();

dr["StudentId"] = 100;

dr["StudentName"] = "Santhosh";

dt.Rows.Add(dr);

dr = dt.NewRow();

dr["StudentId"] = 101;

dr["StudentName"] = "Kumar";

dt.Rows.Add(dr);

}

Step 3 : Now we need to flip this DataTable, so that we can get columns as rows.

Code

public static DataTable FlipDataTable(DataTable dt)

{

DataTable table = new DataTable();

//Get all the rows and change into columns

for (int i = 0; i <= dt.Rows.Count; i++)

{

table.Columns.Add(Convert.ToString(i));

}

DataRow dr;

//get all the columns and make it as rows

for (int j = 0; j < dt.Columns.Count; j++)

{

dr = table.NewRow();

dr[0] = dt.Columns[j].ToString();

for (int k = 1; k <= dt.Rows.Count; k++)

dr[k] = dt.Rows[k - 1][j];

table.Rows.Add(dr);

}

return table;

}

The above method will flip columns into rows.

Step 4 : Now I am going to bind the original DataTable to a GridView gvColumnsAsColumns and the flipped DataTable to gvColumnsAsRows. Add the following code in the page_load event.

Code

//Bind datatable with columns as columns

gvColumnsAsColumns.DataSource = dt;

gvColumnsAsColumns.DataBind();

//Bind datatable with columns as rows

gvColumnsAsRows.DataSource = FlipDataTable(dt);

gvColumnsAsRows.DataBind();

gvColumnsAsRows.HeaderRow.Visible = false;

Step 5 : Run the application and see the difference in the GridViews.

img1.gif

For the complete source code, please find the attached solution.