簡體   English   中英

C# - DataGridView無法添加行?

[英]C# - DataGridView can't add row?

我有一個簡單的C#Windows窗體應用程序,它應該顯示一個DataGridView。 作為DataBinding,我使用了一個Object(選擇了一個名為Car的類),這就是它的樣子:

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 ,表示無法找到我的構造函數。

您的Car類需要一個無參數構造函數,您的數據源需要類似於BindingList

將Car類更改為:

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,但BindingSource提供了一些有時可能需要的額外功能。


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

設置綁定:

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

您需要添加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();
    }
}

我最近發現,如果使用IBindingList實現自己的綁定列表,除了AllowNew之外,你必須在SupportsChangeNotification中返回true

DataGridView.AllowUserToAddRowsMSDN文章僅指定以下注釋:

如果DataGridView綁定到數據,則如果此屬性和數據源的IBindingList.AllowNew屬性都設置為true,則允許用戶添加行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM