Library code snippets

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 .

Comments

  1. 01 Jan 1999 at 00:00

    This thread is for discussions of Databinding SqlTypes.

Leave a comment

Sign in or Join us (it's free).

Dan Glass

Related podcasts

Events coming up

  • Mar 15

    DevWeek 2010

    London, United Kingdom

    DevWeek is Europe’s leading independent conference for software developers, database professionals and IT architects, and features expert speakers on a wide range of topics, including .NET 4.0, Silverlight 3, WCF 4, Visual Studio 2010, REST, Windows Workflow 4, Thread Synchronization, ASP.NET 4.0, SQL Server 2008 R2, LINQ, Unit Testing, CLR & C# 4.0, .NET Patterns, WPF 4, F#, Windows Azure, ADO.NET, Entity Framework, Debugging, T-SQL Tips & Tricks, and more.

We'd love to hear what you think! Submit ideas or give us feedback