February 27, 2012

GridView Sorting for Dynamically created columns

Below is the code for sorting on columns in dynamically bounded gridview


ExGridViewSorting .aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ExGridViewSorting.aspx.cs" Inherits="ExGridViewSorting" %>


<!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 runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <asp:GridView ID="GridView1" runat="server" onsorting="GridView1_Sorting" AllowSorting="true">
        </asp:GridView>
    
    </div>
    </form>
</body>
</html>



ExGridViewSorting .aspx.cs


using System;
using System.Collections.Generic;


using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
public partial class ExGridViewSorting : System.Web.UI.Page
{
    SqlConnection connObj = new SqlConnection();
    DataSet ds = new DataSet();
    SqlDataAdapter objAdapter;
    
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {


            FillGrid();
        }
    }


    private void FillGrid()
    {
        connObj.ConnectionString = ConfigurationManager.ConnectionStrings["DotNetTrainingConnectionString"].ToString();
        connObj.Open();


        SqlCommand objCommand = new SqlCommand("Select * from account", connObj);


        objAdapter = new SqlDataAdapter(objCommand);
        objAdapter.Fill(ds);
        connObj.Close();
        GridView1.DataSource = ds.Tables[0];
        ViewState["dtbl"] = ds.Tables[0];
        GridView1.DataBind();


    }
    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        DataTable dataTable = ViewState["dtbl"] as DataTable;
   
        if(dataTable!=null)
        {
        DataView  dvSortedView = new  DataView(dataTable);
       
            //string order=" asc";
            dvSortedView.Sort = e.SortExpression + " " + getSortDirection(e.SortDirection);
        GridView1.DataSource = dvSortedView;
        GridView1.DataBind();
        }
    }


    private string getSortDirection(SortDirection sortDirection)
    {
        string newSortDirection = String.Empty;


        switch (sortDirection)
        {
            case SortDirection.Ascending:
                newSortDirection = "ASC";
                break;


            case SortDirection.Descending:
                newSortDirection = "DESC";
                break;
        }


        return newSortDirection;
    }


}









No comments:

Post a Comment

Post a Comment