Getting the values from a Datatable column

|

I couldn't find any better, reusable way to get all the values from a specific column of a datatable, strongly typed than the snippet below:

        internal class DataColumnConverter<T>
        {
            internal T[] GetValuesAsArray(DataTable data, string columnName)
            {
                List<T> values = new List<T>();
                foreach (DataRow r in data.Rows)
                {
                    values.Add((T)r[columnName]);
                }
                return values.ToArray();
            }
        }

Things it's missing:

  • Type Cast checking on the type of items in the DataTables' column that's specified
  • Checking that the column specified exists
  • Handling of a column which contains nullable values (Could <T> be passed as, for example int? to cater for this? maybe! Or perhaps null's could be stripped out...)

About this Entry

This page contains a single entry by Rob published on January 25, 2008 10:00 AM.

ASP.net: Viewstate was the previous entry in this blog.

Describing ASP.net Control properties declaratively is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Powered by Movable Type 4.23-en