我的博客园

.NET,Ajax,DataBase,Javascript
  博客园  :: 首页  :: 新随笔  :: 订阅 订阅  :: 管理

DataGridView 控件绑定List<T>

Posted on 2010-06-29 01:30  ymmt  阅读(2400)  评论(0编辑  收藏  举报

DataGridView 控件绑定List<T>示例:

虽然最终只需要几行简单的代码就可完成绑定,可是由于一些小问题搞了半天才显示出来。

有一点注意,要显示的数据结构中,指向对象的属性,必须是属性,而不能字段!即使是public也不行!

 

代码
using System;
using System.Windows.Forms;


public class DataBind : Form
{
private DataGridView dataGridView1 = new DataGridView();
private BindingSource bindingSource1 = new BindingSource();

public DataBind ()
{
this.Load += new System.EventHandler(DataBind _Load);
}

private void DataBind _Load(object sender, System.EventArgs e)
{

DataGridViewTextBoxColumn col1
= new DataGridViewTextBoxColumn();
col1.HeaderText
= "ID";
col1.DataPropertyName
= "ID";
col1.Name
= "ID";
DataGridViewTextBoxColumn col2
= new DataGridViewTextBoxColumn();
col2.HeaderText
= "姓名";
col2.DataPropertyName
= "Name";
col2.Name
= "Name";
this.dataGridView1.Columns.Add(col1);
this.dataGridView1.Columns.Add(col2);

IList
<UserData> list = new List<UserData>();
list.Add(
new UserData("001", "tom"));
list.Add(
new UserData("002", "bill"));
this.dataGridView1.DataSource = list;

}

#region "business object"
public class UserData
{
private string _ID;
private string _Name;
public string ID;
//public string ID
//{
// get { return _ID; }
// set { _ID = value; }
//}

public string Name
{
get { return _Name; }
set { _Name = value; }
}

public UserData(string id, string name)
{
_ID
= id;
_Name
= name;
}

#endregion

[STAThread]
public static void Main()
{
Application.Run(
new DataBind());
}

}

 

hello everyone!