关于DataGridView的数据源两个值得注意的小问题

1. LINQ的查询结果无法直接作为DataGridView的数据源

DataGridView的DataSource属性为object类型,但并不意味着任何类型都可以作为DataGridView的数据源。DataGridView的数据源必须是实现以下接口的任意类型:

    (1)IList 接口,包括一维数组。

    (2)IListSource 接口,例如,DataTable和DataSet类。

    (3)IBindingList 接口,例如,BindingList<T>类。

    (4)IBindingListView 接口,例如,BindingSource类。

而LINQ查询结果为IEnumerable<T>或IQueryable<T>类型,如果直接作为数据源绑定到DataGridView,将无法显示任何内容。Enumerable类为IEnumerable<T>接口定义了一系列扩展方法,其中的ToList<T>方法可以将IEnumerable<T>转换为List<T>。这样,就可以绑定到DataGridView了。如

var names = from u in list select u.Name;
dataGridView1.DataSource = names.ToList();

2. 字符串无法直接作为DataGridView的数据源

如果将List<string>绑定到DataGridView,往往会想当然的认为字符串会作为DataGridView的内容显示。然而实际显示的却是字符串的长度,这是为什么呢?如

dataGridView1.DataSource = new List<string> { "just", "a", "test" };

image

DataGridView默认情况下会显示所绑定对象的属性,如绑定一个List<User>,User的Name、Age、Gender等属性会作为Column的内容显示出来。对于一个字符串来说,只有一个实例属性Length,因此显示的即为字符串的长度了。当然,如果有其他属性存在,仍然会作为Column显示出来。

要想使DataGridView显示字符串集合,可以使用匿名类型将字符串进行包装:

var test = new List<string> { "just", "a", "test" };
dataGridView1.DataSource = (from s in test select new { s }).ToList();

image

posted @ 2009-08-04 16:18  麒麟.NET  阅读(2770)  评论(2编辑  收藏  举报