简体   繁体   English

数据网格视图错误

[英]Error with data grid view

I'm having problem with datagrid view. 我在使用datagrid视图时遇到问题。 I have attached an image with the code & error message. 我已经在图片中附加了代码和错误消息。 I want to know the reason of this error. 我想知道此错误的原因。 Thanks. 谢谢。 在此处输入图片说明

Instead of setting the DataMember simply call the bind method dataGridView1.DataBind() . 无需设置DataMember只需调用绑定方法dataGridView1.DataBind() As stated by MSDN the DataMember is used for the following: MSDN所述, DataMember用于以下用途:

Gets or sets the name of the list or table in the data source for which the DataGridView is displaying data. 获取或设置DataGridView正在为其显示数据的数据源中的列表或表的名称。

You don't need the LINQ query. 您不需要LINQ查询。 just set the list as the DataSource. 只需将列表设置为数据源即可。 There is no need to set the DataMember in this case. 在这种情况下,无需设置DataMember。

    private void Form4_Load(object sender, EventArgs e)
    {
        List<Products> productList = new List<Products>()
        {
            new Products{ProductName = "P1", ProductPrice = 56, Category = "c1"},
            new Products{ProductName = "P2", ProductPrice = 36, Category = "c1"}    
        };

        //var p = from s in productList select s;

        dataGridView1.DataSource = productList;
        //dataGridView1.DataMember = p.ToString();
    }

EDIT 编辑

LINQ query is returning IEnumerable ; LINQ查询返回IEnumerable ; however the DataGridView class supports the standard Windows Forms data-binding model. 但是,DataGridView类支持标准的Windows窗体数据绑定模型。 This means the data source can be of any type that implements one of the following interfaces: IList, IListSource, IBindingList, and IBindingListView. 这意味着数据源可以是实现以下接口之一的任何类型:IList,IListSource,IBindingList和IBindingListView。 So you will need to call ToList() to your LINQ result. 因此,您将需要对LINQ结果调用ToList() Read more about this on this MSDN Link 在此MSDN链接上了解有关此的更多信息

However in your case doing this is same as setting productList as DataSource (I mean the results will be the same, as there is no sorting or grouping involved in the LINQ query). 但是,在您的情况下,这与将productList设置为DataSource相同(我的意思是结果将是相同的,因为LINQ查询中不涉及排序或分组)。

If you want to play with LINQ, try this out (your list will be ordered by ProductPrice in ascending order) 如果您想玩LINQ,请尝试一下(您的列表将按ProductPrice升序排列)

   var p = from s in productList orderby s.ProductPrice select s;
   dataGridView1.DataSource = p.ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM