Click here to Skip to main content
15,886,199 members
Articles / Web Development / HTML
Article

CustomizeGridviewControl

Rate me:
Please Sign up or sign in to vote.
1.33/5 (4 votes)
2 Apr 2008CPOL 28K   171   21   2
CustomizeGridviewControl

Introduction

This Article is show you that a customize gridview control with all thing sorting pagiing is done on page only you have pass columns to Gridview

Background

Using Gridview with Rapid Development

Using the code

A brief description of how to use the article or code. The class names, the methods and properties, any tricks or tips.

Blocks of code should be set as style "Formatted" like this:

           using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MyDataAccesLayer;

public partial class MyGrid : System.Web.UI.UserControl
{
    #region Declarion and Variables
    DBAccess objDBAccess = new DBAccess();
    string userID = "";
    static int i = 0;
    string resid = "";
    DataSet ds = null;
    #endregion

    #region Constructor and Property
    private string GridViewSortDirection
    {
        get
        {
            return ViewState["SortDirection"] as string ?? "ASC";
        }
        set
        {
            ViewState["SortDirection"] = value;
        }
    }
    private string GridViewSortExpression
    {
        get
        {
            return ViewState["SortExpression"] as string ?? string.Empty;
        }
        set
        {
            ViewState["SortExpression"] = value;
        }
    }
    private string GetSortDirection()
    {
        switch( GridViewSortDirection )
        {
            case "ASC":
                GridViewSortDirection = "DESC";
                break;
            case "DESC":
                GridViewSortDirection = "ASC";
                break;
        }
        return GridViewSortDirection;
    }
    #endregion

    #region Events
    protected void Page_Load( object sender, EventArgs e )
    {
        if( !IsPostBack )
        {
            try
            {
                GetData();
            }
            catch( Exception ex )
            {
                Response.Write( ex.Message );
            }
        }
    }
    protected void GridView1_RowDataBound( object sender, GridViewRowEventArgs e )
    {
        try
        {
            if( e.Row.RowType == DataControlRowType.DataRow )
            {
                userID = GridView1.DataKeys[e.Row.RowIndex][1].ToString();
                resid = GridView1.DataKeys[e.Row.RowIndex][0].ToString();
                HyperLink lnkFinalSettlement = (HyperLink) e.Row.FindControl( "lnkFinalSettlement" );
                lnkFinalSettlement.Attributes.Add( "onmouseover", "this.style.cursor='hand'" );
                lnkFinalSettlement.Attributes.Add( "onclick", "javascript:window.open('Default.aspx?userID=" + userID + "&resid=" + resid + "','','','');" );
                Label lblResaon = (Label) e.Row.FindControl( "lblResaon" );
            }
        }
        catch( Exception ex )
        {
            Response.Write( ex.Message );
        }
    }
    protected void GridView1_PageIndexChanging( object sender, GridViewPageEventArgs e )
    {
        try
        {
            GridView1.PageIndex = e.NewPageIndex;
            GetData();
        }
        catch( Exception ex )
        {
            Response.Write( ex.Message );
        }
    }
    public void Paging( object sender, ImageClickEventArgs e )
    {
        ImageButton btn = (ImageButton) sender;
        switch( btn.ID )
        {
            case "btnPageFirst":
                GridView1.PageIndex = 0;
                lblCurrentPage.Text = GridView1.PageIndex.ToString();
                GetData();
                break;
            case "btnPageBackward":
                if( ( GridView1.PageIndex > 0 ) )
                {
                    GridView1.PageIndex -= 1;
                    lblCurrentPage.Text = GridView1.PageIndex.ToString();
                    GetData();
                }
                break;
            case "btnPageForward":
                if( ( GridView1.PageIndex < ( GridView1.PageCount - 1 ) ) )
                {
                    GridView1.PageIndex += 1;
                    lblCurrentPage.Text = GridView1.PageIndex.ToString();
                    GetData();
                }
                break;
            case "btnPageLast":
                GridView1.PageIndex = GridView1.PageCount - 1;
                lblCurrentPage.Text = GridView1.PageIndex.ToString();
                GetData();
                break;
            default:

                break;
        }
    }
    protected void GridViewSorting( object sender, EventArgs e )
    {
        LinkButton btn = (LinkButton) sender;
        GridViewSortExpression = btn.ID;
        int pageIndex = GridView1.PageIndex;
        GridView1.DataSource = SortDataTable( GetDataTable(), false );
        GridView1.DataBind();
        GridView1.PageIndex = pageIndex;
    }
    #endregion

    #region Methods
    protected DataTable GetDataTable()
    {
        string qry = "fs_get_New_Resignation @DEPT_ID=1";
        ds = (DataSet) objDBAccess.ExecuteQuery( qry, ReturnType.DataSetType );
        return ds.Tables[0];
    }
    protected void GetData()
    {
        GridView1.DataSource = SortDataTable( GetDataTable(), true );
        GridView1.DataBind();
        lblCurrentPage.Text = Convert.ToString( GridView1.PageIndex + 1 );
        lblTotalPage.Text = Convert.ToString( GridView1.PageCount );
    }
    protected DataView SortDataTable( DataTable dataTable, bool isPageIndexChanging )
    {
        if( dataTable != null )
        {
            DataView dataView = new DataView( dataTable );
            if( GridViewSortExpression != string.Empty )
            {
                if( isPageIndexChanging )
                {
                    dataView.Sort = string.Format( "{0} {1}", GridViewSortExpression, GridViewSortDirection );
                }
                else
                {
                    dataView.Sort = string.Format( "{0} {1}", GridViewSortExpression, GetSortDirection() );
                }
            }
            return dataView;
        }
        else
        {
            return new DataView();
        }
    }
    #endregion

}

HTML
      
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="MyGrid.ascx.cs" Inherits="MyGrid" %>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <table cellpadding="0" cellspacing="0" border="0" width="100%">
            <tr>
                <td>
                    <table width="100%" cellpadding="0" cellspacing="0">
                        <tr>
                            <td align="center" colspan="5">
                            </td>
                        </tr>
                        <tr>
                            <td align="center" colspan="5">
                                <asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1"
                                    DisplayAfter="5" DynamicLayout="true">
                                    <ProgressTemplate>
                                        <div style="width: 100%" align="center" class="Field">
                                            ....loading.....<br />
                                            
                                            <img src="images/ajax-loader.gif" />
                                        </div>
                                    </ProgressTemplate>
                                </asp:UpdateProgress>
                            </td>
                        </tr>
                        <tr>
                            <td align="center" colspan="5">
                                 
                            </td>
                        </tr>
                        <tr>
                            <td class="SubHeading" width="18%" align="center">
                                <asp:LinkButton ID="EmployeeName" runat="server" Text="Employee Name" OnClick="GridViewSorting"></asp:LinkButton></td>
                            <td class="SubHeading" width="47%" align="center">
                                <asp:LinkButton ID="Reason" runat="server" Text="Reason For Sepration" OnClick="GridViewSorting"></asp:LinkButton>
                            </td>
                            <td class="SubHeading" width="11%" align="center">
                                <asp:LinkButton ID="Resignation_Date" runat="server" Text="Resignation Date" OnClick="GridViewSorting"></asp:LinkButton>
                            </td>
                            <td class="SubHeading" width="11%" align="center">
                                Clearance Form
                            </td>
                            <td class="SubHeading" width="13%" align="center">
                                Final Settlement
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Panel ID="pnlResignation" runat="server" ScrollBars="Vertical" Height="500px"
                        Width="100%">
                        <table width="100%">
                            <tr>
                                <td valign="top">
                                    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Resignation_ID,userID"
                                        Width="100%" CellPadding="2" OnRowDataBound="GridView1_RowDataBound" OnPageIndexChanging="GridView1_PageIndexChanging"
                                        ForeColor="#333333" ShowHeader="False" AllowPaging="True" PageSize="20">
                                        <Columns>
                                            <asp:BoundField DataField="EmployeeName">
                                                <ItemStyle Width="18%" VerticalAlign="Top" />
                                            </asp:BoundField>
                                            <asp:TemplateField>
                                                <ItemTemplate>
                                                    <asp:Label ID="lblResaon" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"Reason")%>'></asp:Label>
                                                </ItemTemplate>
                                                <ItemStyle Width="47%" />
                                            </asp:TemplateField>
                                            <asp:BoundField DataField="Resignation_Date">
                                                <ItemStyle Width="13%" HorizontalAlign="Center" />
                                            </asp:BoundField>
                                            <asp:HyperLinkField Text="Clearance Form" DataNavigateUrlFields="Resignation_ID,UserID,Dept_ID"
                                                DataNavigateUrlFormatString="~/clearance-form.aspx?resignationid={0}&amp;userid={1}&amp;deptid={2}">
                                                <ItemStyle Width="11%" HorizontalAlign="Center" />
                                            </asp:HyperLinkField>
                                            <asp:TemplateField>
                                                <ItemTemplate>
                                                    <asp:HyperLink ID="lnkFinalSettlement" runat="server" Text="Final Settlement" Style="text-decoration: underline;">
                                                    </asp:HyperLink>
                                                </ItemTemplate>
                                                <ItemStyle Width="13%" HorizontalAlign="Center" />
                                            </asp:TemplateField>
                                        </Columns>
                                        <RowStyle CssClass="rptd1" />
                                        <AlternatingRowStyle CssClass="rptd2" />
                                        <PagerStyle CssClass="SubHeading" />
                                        <PagerSettings Visible="False" />
                                    </asp:GridView>
                                </td>
                            </tr>
                        </table>
                    </asp:Panel>
                    <%--  <Triggers>
                    <asp:AsyncPostBackTrigger ControlID="btnPageBackward" EventName="Click" />
                    <asp:AsyncPostBackTrigger ControlID="btnPageFirst" EventName="Click" />
                    <asp:AsyncPostBackTrigger ControlID="btnPageForward" EventName="Click" />
                    <asp:AsyncPostBackTrigger ControlID="btnPageLast" EventName="Click" />
                    <asp:AsyncPostBackTrigger ControlID="Resignation_Date" EventName="Click" />
                    <asp:AsyncPostBackTrigger ControlID="Reason" EventName="Click" />
                    <asp:AsyncPostBackTrigger ControlID="EmployeeName" EventName="Click" />
                </Triggers>--%>
                </td>
            </tr>
            <tr>
                <td align="right">
                    <table width="100%" cellpadding="0" cellspacing="0">
                        <tr>
                            <td class="SubHeading" width="25%" align="center">
                            </td>
                            <td class="SubHeading" width="25%" align="center">
                            </td>
                            <td class="SubHeading" width="25%" align="center">
                            </td>
                            <td class="SubHeading" width="25%" align="center">
                                Page
                                <asp:Label ID="lblCurrentPage" runat="server" Text=""></asp:Label>
                                of
                                <asp:Label ID="lblTotalPage" runat="server" Text=""></asp:Label>
                                <asp:ImageButton ID="btnPageFirst" runat="server" ImageAlign="Middle" ImageUrl="~/images/first.gif"
                                    OnClick="Paging" />
                                <asp:ImageButton ID="btnPageBackward" runat="server" ImageAlign="Middle" ImageUrl="~/images/previous.gif"
                                    OnClick="Paging" />
                                <asp:ImageButton ID="btnPageForward" runat="server" ImageAlign="Middle" ImageUrl="~/images/next.gif"
                                    OnClick="Paging" />
                                <asp:ImageButton ID="btnPageLast" runat="server" ImageAlign="Middle" ImageUrl="~/images/last.gif"
                                    OnClick="Paging" />
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
    </ContentTemplate>
</asp:UpdatePanel>

Remember to set the Language of your code snippet using the Language dropdown.

Use the "var" button to to wrap Variable or class names in &lt;code&gt; tags like this.


History

Keep a running update of any changes or improvements you've made here.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Axact Pvt Ltd
Pakistan Pakistan
Sr Software Engineer
Axact Pvt Ltd
Karachi Pakistan

Comments and Discussions

 
GeneralMy vote of 1 Pin
asdqwewqe12-Jan-10 7:08
asdqwewqe12-Jan-10 7:08 
QuestionCould you walk me through this Pin
s_e_jean14-Nov-08 6:14
s_e_jean14-Nov-08 6:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.