Object Binding in DataGrid with C#

AuthorDate Of SubmissionUser Level
Mahesh Chand06/15/2004Beginner

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.

  • 0
    点赞
  • 0
    收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页
评论

打赏作者

cgmx

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值