Databinding SqlTypes

Page 1 of 2
  1. Introduction
  2. The Solution

Introduction

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 .

You might also like...

Comments

Dan Glass

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Weeks of coding can save you hours of planning.”