0

当我使用以下代码时,会发生错误

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(); 

使用 bindingSource3.AddNew() 时出错;

错误:无法在 '<>f__AnonymousType1 2[[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]]' 如果您设置 AllowNew=true 并处理AddingNew 事件,请输入。

4

1 回答 1

1

AddNew当您DataSource是匿名类型对象的集合时,您不能调用。

所以你必须声明你的自定义类:

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

并更改您的查询以返回该对象的集合而不是匿名对象:

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();
于 2013-04-14T21:00:39.340 回答