Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version

Advanced ASPX GridView Pagination and Data Entities

, 14 Feb 2013
ASP.NET based software system skeleton that uses the ASPX GridView control and advanced pagination for displaying a list of data entities loaded from the database, and the ASP.NET AJAX ModalPopupExtender control for creating new entities or for editing entities from the grid.
#region Copyright (c) 2010 Raul Iloc
/*
{***************************************************************************}
{                                                                           }
{       Copyright (c) 2010  RAUL ILOC (rauliloc@yahoo.com)                  }
{       ALL RIGHTS RESERVED                                                 }
{                                                                           }
{   THE WORK IS PROVIDED UNDER THE TERMS OF THIS CODE PROJECT OPEN LICENSE. }
{   THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW.         }
{   ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE         }
{   OR COPYRIGHT LAW IS PROHIBITED.                                         }
{                                                                           }
{                                                                           }
{  BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HEREIN, YOU ACCEPT AND     }
{  AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. THE AUTHOR GRANTS YOU    }
{  THE RIGHTS CONTAINED HEREIN IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH  }
{  TERMS AND CONDITIONS. IF YOU DO NOT AGREE TO ACCEPT AND BE BOUND BY THE  }
{  TERMS OF THIS LICENSE, YOU CANNOT MAKE ANY USE OF THE WORK.              }
{                                                                           }
{***************************************************************************}
*/
#endregion Copyright (c) 2010 Raul Iloc

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 Ra.GridView.Data;
using Ra.GridView.Util;
using Ra.GridView.Web.Data;

namespace Ra.GridView.Web
{
    /// <summary>
    /// Defines the contat list page.
    /// </summary>
    public partial class ContactListPage : BaseListPage
    {
        /// <summary>
        /// Gets the selected group ID from filter.
        /// </summary>
        public int GroupID
        {
            get
            {
                int groupID = 0;
                int.TryParse(_groupDropDownList.SelectedItem.Value, out groupID);
                //
                return groupID;
            }
        }

        /// <summary>
        /// Raises Init event used to associate this page with its data. 
        /// </summary>
        /// <param name="e">The arguments.</param>
        protected override void OnInit(EventArgs e)
        {
            //
            // ContactListPageData must be linked here with its page. 
            //
            ContactListPageData.Page = this;
            //
            base.OnInit(e);
        }

        /// <summary>
        /// Init event used to init the filter controls.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The arguments.</param>
        protected void Page_Init(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                try
                {
                    //
                    // Init the center drop down list used as filter control
                    //
                    List<Group> centerList = DataContext.Groups.ToList<Group>();
                    SortedDictionary<string, int> sortedData = new SortedDictionary<string, int>();
                    foreach (Group center in centerList)
                    {
                        if (!sortedData.ContainsValue(center.ID))
                            sortedData.Add(center.Name, center.ID);
                    }
                    //
                    _groupDropDownList.DataSource = sortedData;
                    _groupDropDownList.DataValueField = "value";
                    _groupDropDownList.DataTextField = "key";
                    _groupDropDownList.DataBind();
                    //
                    _groupDropDownList.Items.Insert(0, new ListItem("All Groups", "0"));
                    //
                    _groupDropDownList.SelectedIndex = 0;
                }
                catch (Exception ex)
                {
                    RaGridViewEventLog.LogException(ex);
                    this.ErrorMessage = "Error in loading the data from the database!";
                }
            }
        }

        /// <summary>
        /// Load event used to init the page.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The arguments.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
               try
                {
                    if (Request.QueryString["ContactID"] != null)
                    {
                        int ContactID;
                        int.TryParse(Request.QueryString["ContactID"], out ContactID);
                        ContactListPageData.ContactID = ContactID; // Search only one Contact!
                    }
                    else
                    {
                        ContactListPageData.ContactID = 0; // Allow to search by using filter!
                    }
                }
                catch (Exception ex)
                {
                    RaGridViewEventLog.LogException(ex);
                    this.ErrorMessage = "Error in loading the data from the database!";
                }
            }
        }

        /// <summary>
        /// Raised when a button is clicked in the GridView control.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The arguments.</param>
        protected void _contactsGridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "DeleteContact")
            {
                Contact contact = null;
                //
                try
                {
                    int contactID = Convert.ToInt32(e.CommandArgument);
                    //
                    contact = DataContext.Contacts.Single(item => item.ID == contactID);
                    contact.Deleted = true; //Mark as deleted!
                    //
                    DataContext.SaveChanges();
                    //
                    // Refresh the grid!
                    //
                    if (ContactListPageData.ContactID == 0)
                        RefreshGrid(true);
                    else
                        this.Response.Redirect("ContactListPage.aspx", false);
                }
                catch (Exception ex)
                {
                    RaGridViewEventLog.LogException(ex);
                    this.ErrorMessage = "Error in deleting the entity from the database!";
                }
            }
        }

        /// <summary>
        /// Refresh the grid.
        /// </summary>
        /// <param name="afterDelete">Must be true after delete operation.</param>
        private void RefreshGrid(bool afterDelete = false)
        {
            ContactListPageData.AfterDelete = afterDelete;
            _contactsGridView.DataBind();
        }

        /// <summary>
        /// _applyFilterButton Click event used to apply the fiter.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The arguments.</param>
        protected void _applyFilterButton_Click(object sender, EventArgs e)
        {
            //
            // Load data for new filter.
            // Note that the ContactID and NewFilter flags must be set before data binding!
            //
            ContactListPageData.ContactID = 0; 
            ContactListPageData.NewFilter = true;
            _contactsGridView.DataBind();
            _contactsGridView.PageIndex = 0;
        }

        /// <summary>
        /// _contactsGridView RowDataBound event used to link JavaScripts with link buttons.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The arguments.</param>
        protected void _contactsGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
             if (e.Row.RowIndex < 0)
                return;
            //
            DataRow dataRow = ((DataRowView)e.Row.DataItem).Row;
            int userID = (int)dataRow["ID"];
            //
            ImageButton editLinkButton = (ImageButton)e.Row.FindControl("_editLinkButton");
            editLinkButton.Attributes.Add("onClick", "ShowEntityEditor('" + userID + "');return false;");
            //
            ImageButton addNewLinkButton = (ImageButton)e.Row.FindControl("_addNewLinkButton");
            addNewLinkButton.Attributes.Add("onClick", "ShowEntityEditor('0');return false;");
        }

        /// <summary>
        /// _refreshGridPopupButton Click used to refresh the grid.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The arguments.</param>
        protected void _refreshGridPopupButton_Click(object sender, EventArgs e)
        {
            if (Session["NewContactID"] != null)
            {
                int id = (int)Session["NewContactID"];
                Session["NewContactID"] = null;
                //
                // Show only the new created entity! 
                //
                ContactListPageData.ContactID = id; 
                _contactsGridView.DataBind();
            }
            else
            {
                //
                // Refresh the current page of the grid.
                //
                _contactsGridView.DataBind();
            }
        }

    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

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

About the Author

Raul Iloc
Architect SoftCon IT Services
Romania Romania
I'm currently Project Manager and Software Architect for .NET Development at SOFTCON IT Services SRL Timisoara a subsidiary of SOFTCON AG Munich Germany.
 
I am a senior software engineer with about 18 years working experience in software development and about 13 years as Project Manager and Architect.
I have about 12 years working experience in C# and .NET, 7 years working experience in C++ and Visual C++, 2+ years working experience in Java and J2EE.

| Advertise | Privacy | Mobile
Web02 | 2.8.140721.1 | Last Updated 15 Feb 2013
Article Copyright 2010 by Raul Iloc
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid