【问题标题】:C# - DataGridView can't add row?C# - DataGridView 不能添加行?
【发布时间】:2012-07-09 11:19:03
【问题描述】:

我有一个简单的 C# Windows 窗体应用程序,它应该显示一个 DataGridView。作为 DataBinding,我使用了一个对象(选择了一个名为 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,它说找不到我的构造函数。

【问题讨论】:

  • 我认为你需要一个无参数构造函数(因为没有信息可以传递给你的 2 参数构造函数),那么你是如何绑定它的?
  • 我必须在绑定源上使用 AllowNew。

标签: c# datagridview


【解决方案1】:

您的 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 提供了一些有时可能需要的额外功能。


如果由于某种原因您绝对不能添加无参数构造函数,那么您可以处理绑定源的添加新事件并调用 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);
}

【讨论】:

  • BindingList 解决了我的问题。 dataGridView1.DataSource = new BindingList&lt;Car&gt;(carList);
【解决方案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();
    }
}

【讨论】:

    【解决方案3】:

    我最近发现,如果您使用IBindingList 实现自己的绑定列表,除了AllowNew 之外,您还必须在SupportsChangeNotification 中返回true

    DataGridView.AllowUserToAddRowsMSDN 文章仅指定以下备注:

    如果 DataGridView 绑定到数据,如果此属性和数据源的 IBindingList.AllowNew 属性都设置为 true,则允许用户添加行。

    【讨论】:

      猜你喜欢
      • 2018-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-22
      相关资源
      最近更新 更多