Click here to Skip to main content
11,433,997 members (56,486 online)
Click here to Skip to main content
Add your own
alternative version

Advanced ASPX GridView Pagination and Data Entities

, 14 Feb 2013 CPOL
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.
RaGridView.zip
RaGridView.bak
RaGridViewDatabase.zip
RaGridView.bak
RaGridViewSourceCode.zip
CreateEventLogEntry
Properties
Ra.GridView.Data
DataModel.edmx
Properties
Ra.GridView.Util
Properties
RaGridView
bin
AjaxControlToolkit.dll
Data
Diagrams
GuiClassDiagram.cd
Global.asax
Images
Add.gif
Delete.gif
Edit.gif
Header.png
obj
Debug
TempPE
Properties
RaGridView.csproj.user
Scripts
Styles
Images
crossIcon.png
titlebarBack.jpg
#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 Ra.GridView.Util;
using Ra.GridView.Data;

namespace Ra.GridView.Web
{
    /// <summary>
    /// Defines the contact page.
    /// </summary>
    /// <remarks>
    /// This page is used to create and/or to edit a contact entity.
    /// </remarks>
    public partial class ContactPage : BaseEntityPage
    {
        /// <summary>
        /// Gets or sets the ID of the current contact entity.
        /// </summary>
        /// <remarks>
        /// Used to cache the ID of the current contact entity between postbacks!
        /// </remarks>
        private int ContactID
        {
            get
            {
                return (ViewState["ContactID"] == null ? 0 : (int)ViewState["ContactID"]);
            }
            set
            {
                ViewState["ContactID"] = value;
            }
        }

        /// <summary>
        /// Init event used to init the page with global data.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The arguments.</param>
        protected void Page_Init(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                //
                // The page must not cache any data.
                //
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                //
                try
                {
                    //
                    // Clear the used cache.
                    //
                    Session["NewContactID"] = null;
                    //
                    // Init the group 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();
                }
                catch (Exception ex)
                {
                    RaGridViewEventLog.LogException(ex);
                    this.ErrorMessage = "Error in loading the data from the database!";
                }
            }
        }

        /// <summary>
        /// Init event used to int the page with entity data.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The arguments.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (string.IsNullOrEmpty(ID) == false)
                {
                    int contactID = Convert.ToInt32(Request.QueryString["ID"]);
                    ViewState["ContactID"] = contactID;
                    //
                    _titleLiteral.Text = (contactID == 0 ? "New Contact" : "Edit Contact");
                    //
                    Contact contact = CreateOrLoadEntity(contactID);
                    if (contact != null)
                        InitFromEntity(contact);
                }
            }
        }

        /// <summary>
        /// Create or load an entity by its ID.
        /// </summary>
        /// <param name="contactID">The entity ID or 0 for create a new enity.</param>
        /// <returns>The entity or null for errors.</returns>
        private Contact CreateOrLoadEntity(int contactID)
        {
            Contact contact = null;
            if (contactID > 0)
            {
                try
                {
                    //
                    // Load and entity from the database.
                    //
                    contact = DataContext.Contacts.Single(item => item.ID == contactID);
                    if (contact == null)
                        throw new RaGridViewException("Contact not found!");
                }
                catch (Exception ex)
                {
                    RaGridViewEventLog.LogException(ex);
                    this.ErrorMessage = "Error in loading the entity data from the database!";
                }
            }
            else
            {
                //
                // Crete and init a new entity.
                //
                contact = new Contact();
                contact.FirstName = string.Empty;
                contact.LastName = string.Empty;
            }
            //
            return contact;
        }

        /// <summary>
        /// Init the control by using entity data.
        /// </summary>
        /// <param name="contact">The entity.</param>
        private void InitFromEntity(Contact contact)
        {
            _firstNameTextBox.Text = contact.FirstName;
            _lastNameTextBox.Text = contact.LastName;
            _phoneTextBox.Text = (contact.Phone == null ? string.Empty : contact.Phone);
            _emailTextBox.Text = (contact.Email == null ? string.Empty : contact.Email);
            _noteTextBox.Text = (contact.Note == null ? string.Empty : contact.Note);
            //
            _groupDropDownList.SelectedIndex = _groupDropDownList.Items.IndexOf(_groupDropDownList.Items.FindByValue(contact.GroupID.ToString()));
        }

        /// <summary>
        /// _saveButton Click event used to save the user inputs into the database.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The arguments.</param>
        protected void _saveButton_Click(object sender, EventArgs e)
        {
            bool isNewEntity = false;
            Contact contact = CreateOrLoadEntity(this.ContactID);
            //
            if (contact != null)
            {
                try
                {
                    //
                    // Save the user inputs into the entity.
                    //
                    contact.FirstName = _firstNameTextBox.Text;
                    contact.LastName = _lastNameTextBox.Text;
                    //
                    string temp = _phoneTextBox.Text.Trim();
                    contact.Phone = (temp.Length < 1 ? null : temp);
                    //
                    temp = _emailTextBox.Text.Trim();
                    contact.Email = (temp.Length < 1 ? null : temp);
                    //
                    temp = _noteTextBox.Text.Trim();
                    contact.Note = (temp.Length < 1 ? null : temp);
                    //
                    int groupID = 0;
                    int.TryParse(_groupDropDownList.SelectedItem.Value, out groupID);
                    contact.GroupID = groupID;
                    //
                    // Save the changes into the database.
                    // 
                    if (contact.ID == 0)
                    {
                        DataContext.Contacts.AddObject(contact);
                        isNewEntity = true;
                    }
                    //
                    DataContext.SaveChanges();
                }
                catch (Exception ex)
                {
                    RaGridViewEventLog.LogException(ex);
                    this.ErrorMessage = "Error in saving the entity into the database!";
                }
            }
            //
            if (isNewEntity)
            {
                //
                // To comunicate the ID of the new created contact to the parent,
                // we must cache its value!
                //
                Session["NewContactID"] = contact.ID;
            }
            //
            // Run "OnOk()" script. Note that this will close the popup window 
            // by invoking _okPopupButton.click() event on the parent page!
            //
            ClientScript.RegisterStartupScript(this.GetType(), "contactSave", "OnOK();", true);
        }
    }
}

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)

Share

About the Author

Raul Iloc
Program Manager SOFTVISION
Romania Romania
I am Project Manager with about 19 years working experience in software development and about 14 years as Project Manager and Architect.
Follow on   LinkedIn

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150428.2 | Last Updated 15 Feb 2013
Article Copyright 2010 by Raul Iloc
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid