Click here to Skip to main content
15,894,405 members
Articles / Programming Languages / C#

Typed SQLDataReader

Rate me:
Please Sign up or sign in to vote.
4.89/5 (13 votes)
16 Aug 20042 min read 174.3K   946   37  
This article would describe how to read column values based on column names, using SQLDataReader.
using System;
using System.Data.SqlClient;

namespace SmartReading
{
	/// <summary>
	/// Summary description for SmartDataReader.
	/// </summary>
	public sealed class SmartDataReader
	{
		private DateTime defaultDate;
		public SmartDataReader(SqlDataReader reader)
		{
			this.defaultDate = DateTime.MinValue;
			this.reader = reader;
		}

		public int GetInt32(String column)
		{
			int data = (reader.IsDBNull(reader.GetOrdinal(column))) ? (int)0 : (int)reader[column];
			return data;
		}

		public short GetInt16(String column)
		{
			short data = (reader.IsDBNull(reader.GetOrdinal(column))) ? (short)0 : (short)reader[column];
			return data;
		}

		public float GetFloat(String column)
		{
			float data = (reader.IsDBNull(reader.GetOrdinal(column))) ? 0 : float.Parse(reader[column].ToString());
			return data;
		}

		public bool GetBoolean(String column)
		{
			bool data = (reader.IsDBNull(reader.GetOrdinal(column))) ? false : (bool)reader[column];
			return data;
		}

		public String GetString(String column)
		{
			String data = (reader.IsDBNull(reader.GetOrdinal(column))) ? null : reader[column].ToString();
			return data;
		}

		public DateTime GetDateTime(String column)
		{
			DateTime data = (reader.IsDBNull(reader.GetOrdinal(column))) ? defaultDate : (DateTime)reader[column];
			return data;
		}

		public bool Read()
		{
			return this.reader.Read();
		}
		private SqlDataReader reader;
	}
}

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Architect
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions