Click here to Skip to main content
15,893,564 members
Articles / Web Development / ASP.NET

ASP.NET Web Component for editing SQL tables

Rate me:
Please Sign up or sign in to vote.
5.00/5 (4 votes)
29 Nov 2012CPOL11 min read 43K   2.5K   24  
ASP.NET c# component for editing SQL tables with plug-in column format adapter architecture.
/*
 * Code Copyright 2012 by Bill Frisbie
 * 
 * This code is licensed under COPL license.
 * Users are free to use this code, modify it and include it in other work, including works for resale.
 * Please include this notice in the code.
 * Author provides code 'as-is', and assumes no liability for any losses whatsoever arising from its use
 * Contact author at bfrisbie@optonline.net with any questions or suggestions.
 */
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BFCS.Data.Common
{
    /// <summary>
    /// TableAdapter derived class for Date values
    /// </summary>
    class DateTableAdapter : TableAdapter, ITableAdapter
    {
        protected DateTime minDate = DateTime.MinValue;         // minimum allowed date
        protected DateTime maxDate = DateTime.MaxValue;         // maximum allowed date

        // JavaScript snippet template to validate date entry
        private const string JavaScriptValidateTemplate =
            @"if (this.value == '') {return true;} var d = new Date(this.value); if (d.ToString=='Invalid Date') {alert('Invalid date');return false;} var min = new Date('{0}'); var max = new Date('{1}'); if (min>d | d>max){alert('Date out of range');return false;} return true;";

        private string Validator;       // fully-qualified JavaScript validation code string
        /// <summary>
        /// Generic constructor for DateTableAdapter: all dates allowed
        /// </summary>
        /// <param name="validator">SQL statement DbValidator to use</param>
        /// <param name="ColumnName">Table column to use</param>
        public DateTableAdapter(DbValidator validator, string ColumnName)
            : base(validator, ColumnName, typeof(DateTime))
        {
            Validator = null;
        }
        /// <summary>
        /// Constructor that enforces min/max limits
        /// </summary>
        /// <param name="validator">SQL Statement DbValidator to use</param>
        /// <param name="ColumnName">Column to use</param>
        /// <param name="modifier">Modifier: should be [minDate],[maxDate]</param>
        /// <remarks>
        /// Use this constructor to create a TableAdapter that restricts the entered DateTime to minimum
        /// and maximum values; these are passed in the modifier argument
        /// </remarks>
        public DateTableAdapter(DbValidator validator, string ColumnName, string modifier)
            : this(validator, ColumnName)
        {
            string[] modifiers = modifier.Split(",".ToCharArray());
            if (modifiers.Length < 2)
                throw new ArgumentException("Modifier format: <minDate>,<maxDate>");
            if (!DateTime.TryParse(modifiers[0], out minDate))
                throw new ArgumentException(string.Format("MinDate '{0}' is not a valid date or time",
                    modifier[0]));
            if (!DateTime.TryParse(modifiers[1], out maxDate))
                throw new ArgumentException(string.Format("MaxDate '{0}' is not a valid date or time",
                    modifier[1]));
            if (maxDate < minDate)
                throw new ArgumentException(string.Format("MaxDate '{0}' is before MinDate '{1}'"));
            //Validator = string.Format(JavaScriptValidateTemplate, minDate, maxDate);
            Validator = JavaScriptValidateTemplate.Replace("{0}", minDate.ToString()).Replace("{1}", maxDate.ToString());
        }
        /// <summary>
        /// Convert a value to properly formatted displayable string
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        private string DisplayedText(object value)
        {
            if (value is DateTime)
                return ((DateTime)value).ToString("MM/dd/yyyy");
            value = value ?? "";
            return value.ToString();
        }

        #region ITableAdapter Members
        /// <summary>
        /// Given value from table, return control to display it (non-edit row)
        /// </summary>
        /// <param name="value"></param>
        /// <returns>Label that displayes formatted date string</returns>
        public Control DisplayValue(object value)
        {
            Label label = new Label();
            label.Text = DisplayedText(value);
            return label;
        }

        public System.Web.UI.Control EditValue(object value)
        {
            return EditValue(value, false);
        }
        /// <summary>
        /// Given initial value from table, return control used in edit or append row
        /// </summary>
        /// <param name="value">value from table</param>
        /// <param name="Appending">Flag: true if appending, false if editing</param>
        /// <returns>TextBox control for editing value (label if not appending and value is a key)</returns>
        public System.Web.UI.Control EditValue(object value, bool Appending)
        {
            if ((IsKey && !Appending) || !IsWriteable)
                return DisplayValue(value);
            TextBox t = new TextBox();
            t.Text = DisplayedText(value);
            t.MaxLength = 10;
            t.Attributes.Add("onchange", Validator);
            return t;
        }
        /// <summary>
        /// Convert entered value from Form collection to SQL insertion string, checking for error
        /// </summary>
        /// <param name="setting">Entered string from Form collection</param>
        /// <param name="error">(out) error message detected</param>
        /// <returns>value to insert into SQL statement (without delimiters)</returns>
        public virtual string SaveValue(string setting, out string error)
        {
            DateTime v;
            error = "";
            if (setting.Trim() == "")
                return "";          // allow blank string
            if (!DateTime.TryParse(setting, out v))
            {
                error = string.Format("{0} is not a valid date/time", setting);     // string is not a date
            }
            else
            {
                // Check to see if in legal range
                if (v < minDate || v > maxDate)
                    error = string.Format("{0} is not in valid date range {1} - {2}", minDate, maxDate);
            }
            return setting;
        }

        #endregion
    }
}

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)


Written By
Software Developer (Senior) Rovenet, Inc.
United States United States
Bill, who thinks of himself in the third person, has been programming since the dawn of time (1974) in a wide variety of hardware environments (dipswitch settings and paper tape in the beginning), languages (asm, forth, c, c++, c#, basic [visual and unvisualizable]) and industries (graphic arts, medical technology, commercial, website, mobile devices). Corporate clients include DHL, Pitney-Bowes and now-defunct medical equipment midget Q-Med. In his free time, which is all the time, he plays bluegrass guitar, body-boards the oceans of the world and bicycles through Southern California and eastern Long Island, NY.

Comments and Discussions