Object Binding in DataGrid with C#


Introduction

In this article, I will discuss how to bind objects such as an ArrayList to a DataGrid control using C# and ADO.NET.

Binding an ArrayList

If you create an ArrayList and bind it to the DataGrid control, DataGrid does not display the contents. For example, the following code creates an ArrayList objects, add items to it, and binds it to the DataGrid:

ArrayList list = new ArrayList();
list.Add(1);
list.Add(2);
list.Add(3);
dataGrid1.DataSource = list;

The problem with this code is DataGrid is not aware of the contents of the ArrayList. DataGrid can only display contents having a format of schema where there should be a column name and column type.

The Solution

The solution of the problem is to create a class that exposes an integer as its property. Then you create an ArrayList and bind it to the DataGrid. For example, the following code creates an ArrayList of MyClass object, which takes one value as constructor parameter. Here MyClasss exposes this value as an int property.

ArrayList list = new ArrayList();
list.Add(
new MyClass(1);
list.Add(
new MyClass(2);
list.Add(
new MyClass(3);
dataGrid1.DataSource = list;

The Complete Code

Here is a class with integer and string properties.

public class BindingObject
{
private int intMember;
private string stringMember;
private string nullMember;
public BindingObject(int i, string str1, string str2)
{
intMember = i;
stringMember = str1;
nullMember = str2;
}
public int IntMember
{
get { return intMember; }
}
public string StringMember
{
get { return stringMember; }
}
public string NullMember
{
get { return nullMember; }
}
}

Now you can create an ArrayList of this class objects and bind it to the DataGrid as following:

ArrayList list = new ArrayList();
list.Add(
new BindingObject(1, "One", null));
list.Add(
new BindingObject(2, "Two", null));
list.Add(
new BindingObject(3, "Three", null));
dataGrid1.DataSource = list;

The contents would look like the following:

Where StringMember, IntMember, and NullMember are three properties of the object.

See the attached code for more details.

Summary

In this article, you learned how to take advantage of DataGrid binding feature to display the contents of an array of objects.


Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.