Error with data grid view

I'm having problem with datagrid view. I have attached an image with the code & error message. I want to know the reason of this error. Thanks.

Answers


You don't need the LINQ query. just set the list as the DataSource. There is no need to set the DataMember in this case.

    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; however the DataGridView class supports the standard Windows Forms data-binding model. This means the data source can be of any type that implements one of the following interfaces: IList, IListSource, IBindingList, and IBindingListView. So you will need to call ToList() to your LINQ result. Read more about this on this MSDN Link

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).

If you want to play with LINQ, try this out (your list will be ordered by ProductPrice in ascending order)

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

Instead of setting the DataMember simply call the bind method dataGridView1.DataBind(). As stated by MSDN the DataMember is used for the following:

Gets or sets the name of the list or table in the data source for which the DataGridView is displaying data.


Need Your Help

Select parent object from a field in js

javascript oop object field parent

I am relatively new to OOP so I am not sure about the terminology.

Multiple alertViews create error

iphone ios xcode error-handling uialertview

Hello and good afternoon, I'm having some issues here, and to be honest, I don't understand