2013-04-14 43 views
0

當我使用下面的代碼發生錯誤在使用bindingSource3.AddNew錯誤AddNew無法在使用bindingSource3.AddNew()時在'<> f__AnonymousType1`2上調用。

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

誤差();

錯誤:的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__AnonymousType1 -2 - [[System.Int32,mscorlib程序,版本= 4.0.0.0,文化=中性公鑰= b77a5c561934e089],[System.String,mscorlib程序,版本= 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089]]'類型,如果您設置AllowNew = true並處理AddingNew事件。

+1

匿名類是隻讀的,所以'AddNew'是毫無意義的。 – leppie

回答

1

當您的DataSource是匿名類型對象的集合時,不能調用AddNew

所以,你必須聲明你的自定義類:

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(); 
相關問題