0
votes

When I use the following code the error occurs

testtelContext db = new testtelContext();
        var qry = (from p in db.firstlasts
                              join i in db.firstnames
                                  on p.Idfname equals i.Idfname
                              select new 
                              {
                                  id = p.idfl,
                                  name = i.fname

                              }).ToList();
        bindingSource3.DataSource = qry;

        dataGridView5.DataSource = bindingSource3;
        bindingSource3.AddNew(); 

Errors in the use bindingSource3.AddNew();

error:AddNew cannot be called on the '<>f__AnonymousType12[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' type. This type does not have a public default constructor. You can call AddNew on the '<>f__AnonymousType12[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' type if you set AllowNew=true and handle the AddingNew event.

1
Anonymous classes are readonly, so AddNew is pointless.leppie

1 Answers

1
votes

You can't call AddNew when your DataSource is a collection of Anonymous Type objects.

So you have to declare your custom class:

public class BindingItem
{
    public int id { get; set;}
    public string name { get; set; }
}

And change your query to return collection of that objects instead of anonymous ones:

var qry = (from p in db.firstlasts
           join i in db.firstnames on p.Idfname equals i.Idfname
           select new BindingItem 
           {
               id = p.idfl,
               name = i.fname
           }).ToList();