Lets say we have an object, which wraps some data from the database. Eventually we want a collection of them displayed in a DataGrid or some other bindable component. For the purpose of this discussion, we will have a class that wraps a DataRow
, and properties that wrap its cells.
public class DataRowWrapper
{
private DataRow dataRow;
public DataRowWrapper(DataRow dr)
{
this.dataRow = dr;
}
public int ID
{
get { return (int) this.dataRow["ID"]; }
}
public DateTime dtStamp
{
get { return (DateTime) this.dataRow["dtStamp"]; }
set { this.dataRow["dtStamp"] = value; }
}
}
The problem
This example may look all well and good, but unfortunately a cell can be null, and an int or DateTime cannot! Herein lies the problem. This code will throw exceptions on any null data, and we cannot assign null to the values. So we can use SqlTypes which allow null values.
public SqlDateTime dtStamp
{
get
{
if (this.dataRow.IsNull("dtStamp"))
return SqlDateTime.Null;
else
return new SqlDateTime((DateTime)this.dataRow["dtStamp"]);
}
set
{
if ( value.IsNull )
this.dataRow["dtStamp"] = DBNull.Value;
else
this.dataRow["dtStamp"] = value.Value;
}
}
So now we have ruined it for data binding. Data binding does not work for SqlTypes
. SqlTypes
are not editable. I see this as a big oversight, but there is a solution - PropertyDescriptors
.
Comments