Click here to Skip to main content
15,885,366 members
Articles / Desktop Programming / WPF

An Editable ListBox for WPF

Rate me:
Please Sign up or sign in to vote.
4.83/5 (7 votes)
13 May 2009CPOL19 min read 78.2K   3K   23  
A simple to implement editable listbox for WPF.
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Drawing;
using System.Diagnostics;
using EditableListboxApp.Infrastructure;

namespace EditableListboxApp.Modules.Weebit.Services
{
    public class WeebitService : IWeebitService
    {

        const string moduleName = "WeebitSvc";
        DataTable dtData = new DataTable("WeebitData");

        public WeebitService()
        {
            try
            {
                //We're persisting the data using an XML file. If it exists
                //load it if not create the schema.
                string dataFilePath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                if (File.Exists(dataFilePath + "\\WeebitData.xml"))
                {
                    dtData.ReadXml(dataFilePath + "\\WeebitData.xml");
                }
                else
                {
                    CreateTableSchema();
                }
            }
            catch
            {
                Debug.WriteLine("Failed to initialize Weebit data!");
            }
        }
        #region IWeebitService Members
        /// <summary>
        /// Returns null if no exist
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public WeebitData GetWeebit(string name)
        {
            WeebitData data = null;

            if (string.IsNullOrEmpty(name) == false)
            {
                DataRow[] drColl = dtData.Select("name='" + name + "'");

                if (drColl.Length > 0)
                {
                    data = new WeebitData();
                    data.Name = name;
                    data.Description = Convert.ToString(drColl[0]["description"]);
                    data.Length = Convert.ToString(drColl[0]["length"]);
                    data.Width = Convert.ToString(drColl[0]["width"]);
                    data.Height = Convert.ToString(drColl[0]["height"]);
                    data.WeebitColor = Color.FromArgb(Convert.ToInt32(drColl[0]["color"]));
                    data.WeebitType = (WeebitType)(Convert.ToInt32(drColl[0]["type"]));
                }
            }
            return data;
        }
        /// <summary>
        /// Returns empty if none
        /// </summary>
        /// <returns></returns>
        public WeebitData[] GetWeebits()
        {
            List<WeebitData> weebits = new List<WeebitData>();

            foreach (DataRow dr in dtData.Rows)
            {
                WeebitData data = new WeebitData();
                data.Name = Convert.ToString(dr["name"]);
                data.Description = Convert.ToString(dr["description"]);
                data.Length = Convert.ToString(dr["length"]);
                data.Width = Convert.ToString(dr["width"]);
                data.Height = Convert.ToString(dr["height"]);
                data.WeebitColor = Color.FromArgb(Convert.ToInt32(dr["color"]));
                data.WeebitType = (WeebitType)(Convert.ToInt32(dr["type"]));

                weebits.Add(data);
            }

            return weebits.ToArray();
        }
        /// <summary>
        /// Returns empty if none
        /// </summary>
        /// <returns></returns>
        public string[] GetWeebitNames()
        {
            List<string> names = new List<string>();

            foreach (DataRow dr in dtData.Rows)
            {
                names.Add(Convert.ToString(dr["name"]));
            }

            return names.ToArray();
        }
        /// <summary>
        /// Returns false if update failed
        /// </summary>
        /// <param name="weebit"></param>
        /// <returns></returns>
        public bool UpdateWeebit(WeebitData weebit)
        {
            bool returnVal = false;

            if (weebit == null)
                return returnVal;

            try
            {
                string criteria = "name='" + weebit.Name + "'";
                DataRow[] drColl = dtData.Select(criteria);

                if (drColl.Length > 0)
                {
                    drColl[0]["description"] = weebit.Description;
                    drColl[0]["length"] = Convert.ToSingle(weebit.Length);
                    drColl[0]["width"] = Convert.ToSingle(weebit.Width);
                    drColl[0]["height"] = Convert.ToSingle(weebit.Height);
                    drColl[0]["color"] = weebit.WeebitColor.ToArgb();
                    drColl[0]["type"] = (int)weebit.WeebitType;

                    string dataFilePath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

                    dtData.WriteXml(dataFilePath + "\\WeebitData.xml", XmlWriteMode.WriteSchema);
                    returnVal = true;
                    //Publish data changed event
                    //                    eventAggregator.GetEvent<WeebitUpdatedEvent>().Publish(weebit);
                }
            }
            catch (System.Exception ex)
            {
                Debug.WriteLine("Failed to update Weebit data file. Error:" + ex.Message);
            }

            return returnVal;
        }
        /// <summary>
        /// Returns false if failed
        /// </summary>
        /// <param name="weebit"></param>
        /// <returns></returns>
        public bool NewWeebit(WeebitData weebit)
        {
            bool returnVal = false;

            if (weebit == null)
                return returnVal;

            try
            {
                DataRow dr = dtData.NewRow();
                dr["name"] = weebit.Name;
                dr["description"] = weebit.Description;
                dr["length"] = Convert.ToSingle(weebit.Length);
                dr["width"] = Convert.ToSingle(weebit.Width);
                dr["height"] = Convert.ToSingle(weebit.Height);
                dr["color"] = weebit.WeebitColor.ToArgb();
                dr["type"] = (int)weebit.WeebitType;

                dtData.Rows.Add(dr);
                string dataFilePath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

                dtData.WriteXml(dataFilePath + "\\WeebitData.xml", XmlWriteMode.WriteSchema);
                returnVal = true;
                //Publish weebit created event
                //                eventAggregator.GetEvent<WeebitCreatedEvent>().Publish(weebit);
            }
            catch (System.Exception ex)
            {
                Debug.WriteLine("Failed to update Weebit data file! Error:" + ex.Message);
            }

            return returnVal;
        }

        #endregion
        #region db
        /// <summary>
        /// 
        /// </summary>
        void CreateTableSchema()
        {
            DataColumn column = null;

            column = new DataColumn();
            column.DataType = System.Type.GetType("System.Int32");
            column.ColumnName = "id";
            column.ReadOnly = true;
            column.Unique = true;
            column.AutoIncrement = true;
            column.AutoIncrementSeed = 1;
            column.AutoIncrementStep = 1;

            dtData.Columns.Add(column);

            column = new DataColumn();
            column.DataType = System.Type.GetType("System.String");
            column.ColumnName = "name";
            column.ReadOnly = false;
            column.Unique = true;

            dtData.Columns.Add(column);

            column = new DataColumn();
            column.DataType = System.Type.GetType("System.String");
            column.ColumnName = "description";
            column.ReadOnly = false;
            column.Unique = false;

            dtData.Columns.Add(column);

            column = new DataColumn();
            column.DataType = System.Type.GetType("System.Single");
            column.ColumnName = "width";
            column.ReadOnly = false;
            column.Unique = false;

            dtData.Columns.Add(column);

            column = new DataColumn();
            column.DataType = System.Type.GetType("System.Single");
            column.ColumnName = "length";
            column.ReadOnly = false;
            column.Unique = false;

            dtData.Columns.Add(column);

            column = new DataColumn();
            column.DataType = System.Type.GetType("System.Single");
            column.ColumnName = "height";
            column.ReadOnly = false;
            column.Unique = false;

            dtData.Columns.Add(column);

            column = new DataColumn();
            column.DataType = System.Type.GetType("System.Int32");
            column.ColumnName = "color";
            column.ReadOnly = false;
            column.Unique = false;

            dtData.Columns.Add(column);

            column = new DataColumn();
            column.DataType = System.Type.GetType("System.Int32");
            column.ColumnName = "type";
            column.ReadOnly = false;
            column.Unique = false;

            dtData.Columns.Add(column);

            DataColumn[] PrimaryKeyColumns = new DataColumn[1];
            PrimaryKeyColumns[0] = dtData.Columns["id"];
            dtData.PrimaryKey = PrimaryKeyColumns;

        }
        #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)
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions