zoukankan      html  css  js  c++  java
  • 关于DataGridView的数据源两个值得注意的小问题

    转自http://www.cnblogs.com/kirinboy/archive/2009/08/04/1538603.html

    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

  • 相关阅读:
    ABAPNote001
    ABAPNote002
    共享WinCE6.0 下的一个软件升级程序
    EF参数化查询
    VS2010 调用RFC 时注意(.net4.0) 使用nco
    RDLC报表问题
    参数化查询与拼接SQL代码执行测试
    ABAPNOTE 获取释放的定单
    Wince6.0 + xpsp3+VS2005的一些问题
    BackgroundWorker使用备忘
  • 原文地址:https://www.cnblogs.com/ceci/p/1656551.html
Copyright © 2011-2022 走看看