Monday, 22 September 2014

PAGING AND SORTING OPERATIONS ON GRIDVIEW programmatically WITH C#


In This Article We'll See How To Perform Paging And Sorting Operations On Grid View Data Through Coding.

STEPS:

Initially take a gridview control in which you are going to display your data.
As per my requirement i have taken two buttons with the names "show data in grid view" and "show data in repeater" which are displayed as the page loads as shown below.



As it is mentioned on the buttons by clicking them data will be displayed in the respective control.! As Shown Below :


As We Can See In The Above Picture The Data In The Grid View Is Displayed In An Unsorted Order.

NOTE:- THE PAGING IS ALREADY APPLIED ON THE GRID VIEW DISPLAYED ABOVE.

à Lets See How The Paging Can Be Done On The Grid view Programmatically:

Before we perform paging on the grid view control we have to the set few properties as shown below:
·         AllowPaging="true"
·         PageSize="5"[Display no.of  records/items per page. i have assigned the value as per my requirement .u can assign any value as per your criteria].
·         OnPageIndexChanging="Gridview_pageindexchanging"[it is an event which allows you to write your custom code(main event for performing paging) . you can assign any event/method to it].

The Above Mentioned Properties Are Mandatory To Be Assigned To Perform Paging On Grid View.

Here is the code for your designer file (.ascx):

<asp:GridView ID="GridView2" runat="server" AllowSorting="true" >
</asp:GridView>
<asp:TextBox ID="txtusername" runat="server"></asp:TextBox>
<asp:Button ID="btninsert" runat="server" OnClick="btninsert_Click" Text="Insert"/>


<asp:GridView ID="GridView1" runat="server" AllowPaging="true" PageSize="5" OnPageIndexChanging="GridView1_PageIndexChanging" AllowSorting="true" OnSorting="GridView1_Sorting"
     AutoGenerateColumns="False" Width="93px" OnRowCommand="GridView1_RowCommand">
    <Columns>
        <asp:BoundField DataField="EmpName" HeaderText="EmpName" SortExpression="EmpName" />
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Button runat="server" ID="btnget" CommandArgument='<%# Eval("EmpName")%>'  CommandName="get" Text="Get Details" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
    <Columns>
    </Columns>
</asp:GridView>


Here is the code for project file (.cs):

using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Data;

namespace demowebpart.webpartdemo
{
    [ToolboxItemAttribute(false)]
    public partial class webpartdemo : WebPart
    { [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Assert, UnmanagedCode = true)]
        public const string asc = "ASC";
        public const string dsc = "DESC";
        static string str = null;
        public webpartdemo()
        {
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitializeControl();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void btnshowdataingridview_Click(object sender, EventArgs e)
        {
            using (SPSite site = new SPSite("http://vm:22222/sites/saikumar/"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                        txtusername.BorderColor = System.Drawing.Color.Gray;
                        SPList list = web.Lists.TryGetList("deptlist");
                        SPListItemCollection item = list.GetItems();
                        DataTable dt = item.GetDataTable();
                        GridView1.DataSource = dt;
                        GridView1.DataBind();
                        txtusername.Text = "";
                    }
            }
        }
        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "get")
            {
                Button btn = (Button)e.CommandSource;
                using (SPSite site = new SPSite("http://vm:22222/sites/saikumar/"))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList list = web.Lists.TryGetList("deptlist");
                        SPQuery query = new SPQuery();
                        query.Query = "<Where><Eq><FieldRef Name='EmpName' /><Value Type='Text'>" + e.CommandArgument.ToString() + "</Value></Eq></Where>";
                        query.ViewFields = "<FieldRef Name='Title' /><FieldRef Name='EmpName' /><FieldRef Name='dept' />";
                        query.ViewFieldsOnly = true;
                        SPListItemCollection itemcoll = list.GetItems(query);
                        DataTable dt = itemcoll.GetDataTable();
                        GridView2.DataSource = dt;
                        GridView2.DataBind();
                    }
                }
            }
        }

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
           
            GridView1.PageIndex = e.NewPageIndex;
            using (SPSite site = new SPSite("http://vm:22222/sites/saikumar/"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists.TryGetList("deptlist");
                    SPListItemCollection item = list.GetItems();
                    DataTable dt = item.GetDataTable();                 
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                }
            }
        }        
    }
}

 Lets See How Sorting Can Be Done On The Grid view Programmatically:

Before we perform Sorting  on the grid view control we have to the set few properties as shown below:
·         AllowSorting="true"
·         OnSorting="GridView_sorting"


Below Is The Code For Sorting:
(.cs) file:

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        {
            using (SPSite site = new SPSite("http://vm:22222/sites/saikumar/"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists.TryGetList("deptlist");
                    // SPListItem items = list.Items.Add();
                    //items["EmpName"] = txtusername.Text;
                    // items.Update();
                    SPListItemCollection item = list.GetItems();
                    DataTable dt = item.GetDataTable();
                    DataView dv = new DataView(dt);
                    //dv.Sort = e.SortExpression+" "+dsc;
                    if (str == null)
                    {
                        dv.Sort = e.SortExpression + " " + asc;
                    }
                    else if (str == e.SortExpression + " " + dsc)
                    {
                        dv.Sort = e.SortExpression + " " + asc;
                    }
                    else
                    {
                        dv.Sort = e.SortExpression + " " + dsc;
                    }
                    GridView1.DataSource = dv;
                    GridView1.DataBind();
                    str = dv.Sort;
                }
           
            }
           
        }
       
    }
}

After sorting the gridview looks :



Here We Can See The Gridview Is Sorted In Descending Order.
In The Same Way We Can Sort It In Ascending Order As Well.


Thank you 


23 comments: