Rotate Columns to Rows for GridView in asp.net c#
Many times we have seen how to convert row to column or column to row values in gridview in asp.net c# this article we will help you that how to convert row to columns and column to row gridview in asp.net c#
Database:-
Source Code:-
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true">
</asp:GridView>
<br />
<asp:Button ID="btnrow" runat="server" Text="Convert Rows to Columns" OnClick="btnConvert"
CommandArgument="row" />
<asp:Button ID="btncolumns" runat="server" Text="Convert Columns to Rows" OnClick="btnConvert"
CommandArgument="columns" Visible="false" />
</div>
</form>
</body>
</html>
Code Behind (C#):-
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection("Data Source=NEERAJ-PC\\NEERAJ;Initial Catalog=CodeSolution;Persist Security Info=True;User ID=sa; password=12345678");
con.Open();
SqlCommand cmd = new SqlCommand("select * from record", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
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";
}
}
}
protected void btnConvert(object sender, EventArgs e)
{
DataTable dt = (DataTable)ViewState["dt"];
if ((sender as Button).CommandArgument == "row")
{
btnrow.Visible = false;
btncolumns.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
{
btnrow.Visible = true;
btncolumns.Visible = false;
BindGrid(dt, false);
}
}
}
Out-Put:-
Rotate Columns to Rows for GridView in asp.net c#
Reviewed by NEERAJ SRIVASTAVA
on
11:14:00 PM
Rating:
No comments: