Monday, October 29, 2007

Quick method to initialize a strongly-typed DataRow in C#

Last night I needed a routine to initialize all the fields in a datarow of a strongly-typed dataset. I'm working in Visual Studio 2005 and the .Net Framework 2.0. Below is the code that I came up with. Note that I'm slowing switching over to C# for new projects.

This code is not comprehensive of all the possible data types, but it did the trick for me:

private void InitializeNewDataRow(DataRow dr, System.Data.DataColumnCollection dcs) {
object[] fields = dr.ItemArray;
DataColumn[] dca = new DataColumn[fields.Length];
dcs.CopyTo(dca,0);
for (int i=1; i < fields.Length; i++) {
if (dca[i].DataType == typeof(int)) fields[i] = 0;
if (dca[i].DataType == typeof(Int16)) fields[i] = 0;
if (dca[i].DataType == typeof(Int32)) fields[i] = 0;
if (dca[i].DataType == typeof(Int64)) fields[i] = 0;
if (dca[i].DataType == typeof(bool)) fields[i] = false;
if (dca[i].DataType == typeof(string)) fields[i] = string.Empty;
if (dca[i].DataType == typeof(decimal)) fields[i] = 0.0;
if (dca[i].DataType == typeof(DateTime)) fields[i] = DateTime.MinValue;
}
dr.ItemArray = fields;
}
Hope it helps.
Joe Kunk

No comments: