Click here to Skip to main content
15,881,804 members
Articles / Desktop Programming / WPF
Tip/Trick

Create Collection from a DataSet

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
7 Aug 2014CPOL1 min read 11.5K   109   17  
This tip will help you to create a collection from a DataSet

Introduction

Since I started working in WPF, I came to know about Collections. But the tricky part here is previously I was working with Dataset, so it looks like I have started learning a new technology in the data binding perspective, because the Dataset was known to me since I started learning programming but I don't know some of its capabilities/powers either. But now in the WPF world, we used to make use of collection. Now let's start why I am here to write my first article/post/tips and tricks, etc., whatever you call it.

Background

Couple of days ago, I came up with an issue to convert DataTable to Collection in my home developed application and then I started working on this simple solution (not a higher ended solution) and I hope that will help some beginners and intermediate (maybe) developers if they have the same issue.

Code

For this demo, I was using a Person class as shown below:

C#
/// <summary>
    /// Person Class
    /// </summary>
    public class Person
    {
        private int id;
        [XmlElement("id")]
        public int ID
        {
            get { return id; }
            set { id = value; }
        }

        private string name;
        [XmlElement("name")]
        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        private string address;
        [XmlElement("address")]
        public string Address
        {
            get { return address; }
            set { address = value; }
        }

        private DateTime? dob;
        [XmlElement("dob")]
        public DateTime? DateOfBirth
        {
            get { return dob; }
            set { dob = value; }
        }

        private EmpType employeeType = EmpType.Trainee;
        [XmlElement("EmpType")]
        public EmpType EmployeeType
        {
            get { return employeeType; }
            set { employeeType = value; }
        }
    }

    /// <summary>
    /// Person Collection
    /// </summary>
    [Serializable(), XmlRoot("DocumentElement"), XmlType("Person")]
    public class PersonCollection : BindingList<Person>
    {

    }

and an Extension class for DataTable below:

C#
public static class ExtensionsEx
    {
        private static Type collectionType;
        /// <summary>
        /// Lets you convert DataTable to BindingList
        /// </summary>
        /// <typeparam name="T">Collection type</typeparam>
        /// <param name="Dt">DataTable</param>
        /// <param name="bindingList">Collection to fill up</param>
        /// <returns></returns>
        public static Collection<T> GetCollectionfromDataTable<T>
        (this DataTable Dt, Collection<T> bindingList)
        {
            try
            {
                collectionType = bindingList.GetType();
                if (ValidateDataSet<T>(Dt))
                    using (System.IO.MemoryStream xmlStream = new System.IO.MemoryStream())
                    {
                        Dt.WriteXml(xmlStream, XmlWriteMode.IgnoreSchema);

#if DEBUG
                        xmlStream.Position = 0;
                        XmlDocument xd = new XmlDocument();
                        xd.Load(xmlStream);
#endif
                        xmlStream.Position = 0;
                        using (System.Xml.XmlTextReader collectionReader = 
                                new System.Xml.XmlTextReader(xmlStream))
                        {
                            XmlSerializer serializer = new XmlSerializer(collectionType);
                            bindingList = (Collection<T>)serializer.Deserialize(collectionReader);
                        }
                    }
                return bindingList;
            }
            catch { return null; }
        }

        /// <summary>
        /// Just to validate DataTable if it has Name of the Type T.
        /// </summary>
        /// <typeparam name="T"> Type </typeparam>
        /// <param name="Dt">DataTable</param>
        /// <returns> bool </returns>
        private static bool ValidateDataSet<T>(DataTable Dt)
        {
            var s = typeof(T);
            if (collectionType == null) return false;
            if (string.IsNullOrWhiteSpace(Dt.TableName))
            {
                Dt.TableName = s.Name;
                Dt.AcceptChanges();
            }
            return true;
        }
    }

Points of Interest

If your application requires different random number sequences, invoke this constructor repeatedly with different seed values. One way to produce a unique seed value is to make it time-dependent. For example, derive the seed value from the system clock. However, the system clock might not have sufficient resolution to provide different invocations of this constructor with a different seed value (http://msdn.microsoft.com/en-us/library/vstudio/ctssatww(v=vs.100).aspx).

History

This is my first tip. Hope it helps. I will update this soon to support all kinds of data types after learning about them.

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)
India India
http://referencesource.microsoft.com/

Comments and Discussions

 
-- There are no messages in this forum --