Binding to custom objects – level 200

First of all, I rated this post as 200 instead of 300 because I believe that intermediate-level ASP.NET developers SHOULD know about and be using the following technique. When learning data-binding techniques, we see all the samples either bind a single value or bind a DataSet to a grid. It’s very common to put data in a DataSet and bind it. I prefer to bind directly to a collection of custom objects. By creating a collection or array of custom objects (that contain the same data as the DataSet anyway) you benefit from being strongly-typed. You can bind to any property of your object that is a primitive type. For example, if you have:

public class Person
private int m_id;
public string FirstName;
public string LastName;
public int ID
get{ return m_id;}
public string FullName
get{ return FirstName + ” ” + LastName;}
public Person(int id, string firstName, string lastName)
m_id = id;
FirstName = firstName;
LastName = lastName;

you can assemble a collection or array of Person objects and then bind:

Person[] personList = new Person[5];
for(int i = 0; i < 5; i++)
personList[i] = new Person(1, “Jeffrey”, “Palermo”);

DataGrid1.DataSource = personList;

You can bind explicitly or let the grid auto-generate the columns.  You will notice that only the public properties of the Person class were auto-bound:  Even though we had two public fields, these were not automatically bound.  So the public properties are automatically bound.  I have taken advantage of this feature when binding objects that have custom objects as properties.  For instance, if one of the properties of the Person class was “Parent” of type Person, then I would create a property called ParentFullName, and that property would be bind-able.

Also, when binding to a DropDownList, you can write the following code:

myDDL.DataSource = personList;
myDDL.DataTextField = “FullName”;
myDDL.DataValueField = “ID”;

In this way, you can avoid creating a DataSet with the same data as that in your custom objects.  I prefer binding to object properties as opposed to a DataSet.  I think it makes the code more readable and maintainable.

Also, when I bind a list of objects to a DropDownList, I like to have a first entry that says “Select One”, or something similar.  So, after the DataBind() method, I explicitly add a first item:

myDDL.Items.Insert(0, new ListItem(. . .));

Then I have a first item before all the rest.

Finally, binding controls to custom objects is a very powerful feature of ASP.NET, and I think only binding to a DataSet is underusing this powerful feature.