Friday, 14 June 2013

How to Bind the Gridview Vertically...

Hi All ,
I am mentioning the Code to bind the GrdiView in vartically...

<%@ Page Title="" Language="C#" MasterPageFile="~/master.master" AutoEventWireup="true" CodeFile="Testpage.aspx.cs" Inherits="Testpage" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
  
               
    <asp:GridView ID="GridView1" runat="server" ShowHeader="false" RowStyle-Wrap="true" Width="300px" GridLines="Both">

    </asp:GridView>
    
</asp:Content>


.CS page Code..
---------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;


public partial class Testpage : System.Web.UI.Page
{
 protected void Page_Load(object sender, EventArgs e)
 {
        if (!Page.IsPostBack)
        {
            BindGridView();
        }
 }
    private DataTable PivotTable(DataTable origTable)
    {

        DataTable newTable = new DataTable();
        DataRow dr = null;
        //Add Columns to new Table
        for (int i = 0; i <= origTable.Rows.Count; i++)
        {
            newTable.Columns.Add(new DataColumn(origTable.Columns[i].ColumnName, typeof(String)));
        }

        //Execute the Pivot Method
        for (int cols = 0; cols < origTable.Columns.Count; cols++)
        {
            dr = newTable.NewRow();
            for (int rows = 0; rows < origTable.Rows.Count; rows++)
            {
                if (rows < origTable.Columns.Count)
                {
                    dr[0] = origTable.Columns[cols].ColumnName; // Add the Column Name in the first Column
                    dr[rows + 1] = origTable.Rows[rows][cols];
                }
            }
            newTable.Rows.Add(dr); //add the DataRow to the new Table rows collection
        }
        return newTable;
    }

private void BindGridView()
{
        try
        {
            DataTable dt = Library.ExecuteQuery("select * from VipUsersInfo where VID=2");
            if (dt.Rows.Count > 0)
            {
                //Bind the First GridView with the original data from the DataTable
                //GridView1.DataSource = dt;
                //GridView1.DataBind();

                //Pivot the Original data from the DataTable by calling the
                //method PivotTable and pass the dt as the parameter

                DataTable pivotedTable = PivotTable(dt);
                GridView1.DataSource = pivotedTable;
                GridView1.DataBind();
            }
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Fetch Error:";
            msg += ex.Message;
            throw new Exception(msg);
        }
       
}


}


No comments:

Post a Comment