HTML Markup
Below is the HTML Markup where I have n ASP.Net GridView Control and two buttons one to Rotate / Flip / Transpose GridView Columns to Rows and another to Rotate / Flip / Transpose GridView rows to Columns,
- <asp:GridView ID="GridView1" CssClass="Grid" HeaderStyle-CssClass="header" runat="server" AutoGenerateColumns="true">
- </asp:GridView>
- <br />
- <asp:Button ID="btnConvert1" runat="server" Text="Convert Rows to Columns" OnClick="Convert" CommandArgument="1" />
- <asp:Button ID="btnConvert2" runat="server" Text="Convert Columns to Rows" OnClick="Convert" CommandArgument="2" Visible="false" />
C#
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
- DataTable dt = new DataTable();
- dt.Columns.AddRange(new DataColumn[3]
- {
- new DataColumn("Item"), new DataColumn("Quantity"), new DataColumn("Price")
- });
- dt.Rows.Add("Shirt", 145, 500);
- dt.Rows.Add("Jeans", 0, 2000);
- dt.Rows.Add("Trousers", 190, 1545);
- dt.Rows.Add("Tie", 30, 200);
- dt.Rows.Add("Cap", 0, 300);
- dt.Rows.Add("Hat", 90, 350);
- dt.Rows.Add("Scarf", 290, 140);
- dt.Rows.Add("Belt", 150, 400);
- ViewState["dt"] = dt;
- BindGrid(dt, false);
- }
- }
- private void BindGrid(DataTable dt, bool rotate)
- {
- GridView1.ShowHeader = !rotate;
- GridView1.DataSource = dt;
- GridView1.DataBind();
- if (rotate)
- {
- foreach(GridViewRow row in GridView1.Rows)
- {
- row.Cells[0].CssClass = "header";
- }
- }
- }
On btnConvert1 Event:
- protected void Convert(object sender, EventArgs e)
- {
- DataTable dt = (DataTable) ViewState["dt"];
- if ((sender as Button).CommandArgument == "1")
- {
- btnConvert1.Visible = false;
- btnConvert2.Visible = true;
- DataTable dt2 = new DataTable();
- for (int i = 0; i <= dt.Rows.Count; i++)
- {
- dt2.Columns.Add();
- }
- for (int i = 0; i < dt.Columns.Count; i++)
- {
- dt2.Rows.Add();
- dt2.Rows[i][0] = dt.Columns[i].ColumnName;
- }
- for (int i = 0; i < dt.Columns.Count; i++)
- {
- for (int j = 0; j < dt.Rows.Count; j++)
- {
- dt2.Rows[i][j + 1] = dt.Rows[j][i];
- }
- }
- BindGrid(dt2, true);
- } else
- {
- btnConvert1.Visible = true;
- btnConvert2.Visible = false;
- BindGrid(dt, false);
- }
- }