2012-07-09 53 views
7

我有一個簡單的C#Windows窗體應用程序應該顯示一個DataGridView。由於數據綁定我用了一個對象(選擇一個叫做Car類),這是什麼樣子:C# - DataGridView無法添加行?

class Car 
{ 
    public string color { get; set ; } 
    public int maxspeed { get; set; } 

    public Car (string color, int maxspeed) { 
     this.color = color; 
     this.maxspeed = maxspeed; 
    } 
} 

然而,當我在DataGridView屬性AllowUserToAddRows設置爲true,仍然有不小的*,讓我添加行。

有人建議將carBindingSource.AllowAdd設置爲true,但是,當我這樣做時,我得到MissingMethodException其中說我的構造函數找不到。

+0

我想你會需要一個參數少的構造函數(因爲沒有信息可以傳遞給你的2參數構造函數),那麼你怎麼綁定它? – V4Vendetta 2012-07-09 11:25:57

+0

我不得不在我的綁定源上使用AllowNew。 – 2015-05-07 13:49:22

回答

2

您需要添加AddingNew事件處理程序:

public partial class Form1 : Form 
{ 
    private BindingSource carBindingSource = new BindingSource(); 



    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void Form1_Load(object sender, EventArgs e) 
    { 
     dataGridView1.DataSource = carBindingSource; 

     this.carBindingSource.AddingNew += 
     new AddingNewEventHandler(carBindingSource_AddingNew); 

     carBindingSource.AllowNew = true; 



    } 

    void carBindingSource_AddingNew(object sender, AddingNewEventArgs e) 
    { 
     e.NewObject = new Car(); 
    } 
} 
7

您的汽車類需要有一個參數的構造函數和你的數據源的需求會像的BindingList

改變汽車類此:

class Car 
{ 
    public string color { get; set ; } 
    public int maxspeed { get; set; } 

    public Car() { 
    } 

    public Car (string color, int maxspeed) { 
     this.color = color; 
     this.maxspeed = maxspeed; 
    } 
} 

,然後綁定是這樣的:

BindingList<Car> carList = new BindingList<Car>(); 

dataGridView1.DataSource = carList; 

您也可以爲此使用BindingSource,您不必但BindingSource提供了一些額外的功能,有時可能是必需的。


如果由於某種原因,你絕對不能添加參數的構造函數,那麼你可以處理綁定源的添加新的事件,並調用車參數化的構造函數:

設置綁定:

BindingList<Car> carList = new BindingList<Car>(); 
BindingSource bs = new BindingSource(); 
bs.DataSource = carList; 
bs.AddingNew += 
    new AddingNewEventHandler(bindingSource_AddingNew); 

bs.AllowNew = true; 
dataGridView1.DataSource = bs; 

而且處理代碼:

void bindingSource_AddingNew(object sender, AddingNewEventArgs e) 
{ 
    e.NewObject = new Car("",0); 
} 
+1

BindingList解決了我的問題。 'dataGridView1.DataSource = new BindingList (carList);' – styfle 2013-10-23 21:15:26

1

我最近發現如果您使用IBindingList實施自己的綁定列表,則必須在您的SupportsChangeNotification中返回true以及AllowNew

MSDN文章DataGridView.AllowUserToAddRows僅規定而下面的言論:

如果在DataGridView綁定到數據,允許用戶添加行,如果此屬性和數據源的IBindingList.AllowNew財產是設置爲true。