以编程方式将行添加到数据绑定的 DataGridView? [英] Adding rows programatically to a DataGridView that is data bound?

查看:31
本文介绍了以编程方式将行添加到数据绑定的 DataGridView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我似乎无法解决它.我以为这里有人可以帮忙.

I have a problem and I can't seem to be able to solve it. I thought someone here will be able to help out.

我有一个包含客户 DataGridView 的表单.现在,我想将几​​个客户添加到这个 DataGridView 而不实际将它们添加到数据库中.这是因为客户端必须能够创建客户端列表,并在完成后一次性添加它们.

I have a form that has a DataGridView of customers. Now, I want to add several customers to this DataGridView without actually adding them to the database. This is because the client must be able to create a list of clients and when thats done add them all at once.

我已经试过了:

string[] array = {"Microsoft", "Redmond", "Something"}
dataGridView.Rows.Add (array);

现在这无法完成,因为我收到一个异常,说你不能以编程方式将行添加到数据绑定的 DataGridView.

Now this can't be done because I get an exception saying something in the lines of you cant add rows programatically to a DataGridView that is data bound.

现在我也读到这可以通过使用表适配器插入行而不是直接添加行来解决.DGV.但这也是不可能的,因为我在 DGV 中使用自定义标头,因为现有数据是通过 JOIN 获取的,因此如果我通过 TableAdapter 添加它们,我会得到一个异常,即它与数据库表架构不匹配.

Now I have also read that this can be solved by using a table adapter to insert the rows instead of directly adding them via. a DGV. But this is also not possible because I use custom headers in the DGV because existing data is fetched via JOIN's so if I add them via a TableAdapter I get an exception that the it doesn't match the databases table schema.

现在我真的迷路了......有人知道这个问题的(半)优雅解决方案吗?

Now I am really lost... Anyone know of a (halfway) elegant solution to this problem?

谢谢

推荐答案

将您的 DGV 绑定到 BindingList,其中 YourObject 可以是具有属性的简单类反映您的数据库架构.最初从数据库填充BindingList,DGV 会自动将YourObject 实例添加到列表中.当您准备好提交更改时,请从 BindingList 手动提交.

Bind your DGV to a BindingList<YourObject>, where YourObject can be a simple class with properties reflecting your database schema. Initially populate the BindingList from the database, and the DGV will automatically add YourObject instances to the list. When you're ready to commit the changes, do so manually from the BindingList.

这篇关于以编程方式将行添加到数据绑定的 DataGridView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆