Craig Gibbons' Lifeblog lifeblog://tri.eat.net

7Jan/050

C# – Useful static methods for DataRow and SqlDataReader operations

One of the most tedious parts of development is the array of database operations the developer must code into every application. Every time I start a new application I try find better ways to manage data, preferably resulting in significantly less and hopefully higher performing code. During the development of the application I am currently on, I wrote a set of static methods which retrieve field values from DataRow and SqlDataReader objects, probably the 2 most typically used containers for data. While the code below clearly only works for getting strings, the exact same logic can be applied to any data type, I have, in addition, implemented Int32, Double, DateTime and Boolean routines, but have omitted them here for brevity. With the advent of C# v2.0 and generics, this mindless repetition of code will no longer be required, for now, this works well.

public static string GetString(DataRow Source, string ColumnName) {
 return _GetDataRowString(Source, ColumnName, null);
}

public static string GetString(DataRow Source, string ColumnName, string ReturnIfNull) {
 return _GetDataRowString(Source, ColumnName, ReturnIfNull);
}

public static string GetString(SqlDataReader Source, string ColumnName) {
 return _GetReaderString(Source, ColumnName, null);
}

public static string GetString(SqlDataReader Source, string ColumnName, string ReturnIfNull) {
 return _GetReaderString(Source, ColumnName, ReturnIfNull);
}

private static string _GetDataRowString(DataRow Source, string ColumnName, string ReturnIfNull) {
 string val = ReturnIfNull;

 try {
  if(!Convert.IsDBNull(Source[ColumnName])) {
   val = Convert.ToString(Source[ColumnName]);
  }
 } catch {
  return val;
 }

 return val;
}

private static string _GetReaderString(SqlDataReader Source, string ColumnName, string ReturnIfNull) {
 string val = ReturnIfNull;

 try {
  int ColumnNameIndex = Source.GetOrdinal(ColumnName);
  if(!Source.IsDBNull(ColumnNameIndex)) {
   val = Convert.ToString(Source[ColumnNameIndex]);
  }
 } catch {
  return val;
 }

 return val;
}

Filed under: Tech Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

No trackbacks yet.