如何添加新行到datagridview? [英] How to add new row to datagridview?

查看:82
本文介绍了如何添加新行到datagridview?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有DataGridView填充数据源(SQL)的数据。现在我想添加一行,但我不能,因为新数据不能添加到有界的Da​​taGridView ...



我试图: / p>

  dataGridView1.Source = null; 
dataGridView1.Rows.Add(1);

但它清除了我以前在表中的数据。如何做,添加新行而不删除以前的数据?

解决方案

当您设置 DataSource 属性 null ,您实际上是从所有数据=noreferrer> DataGridView (因为它不知道要绑定到什么)。



这里有两个选项。第一个是更新底层数据源。假设这是一个 DataTable 。在这种情况下,您可以执行以下操作:

  DataTable dt = dataGridView1.Source as DataTable; 
dt.Rows.Add(new object [] {...});

然后, DataGridView 将接收更改(请注意,如果您没有绑定到不实现 INotifyCollectionChanged 界面,您必须调用 ResetBindings 方法以使网格刷新。 p>

另一个选项是让 DataGridView 管理这些行。您可以通过使用 添加方法 DataGridViewRowCollection 属性

  foreach(来源的var item)
{
dataGridView1.Rows.Add(1,2,3,...);
}

我不会说第二个解决方案是最佳,但它会工作。



最后,假设您绑定到一个 DataTable (或其他一些实现来自底层数据源的数据),这不会更新底层数据源(这将是一个单独的问题)。


I have DataGridView filled with data from datasource (SQL). Now I want to a add new row, but I can't, because new data can't be added to bounded DataGridView...

I was trying to :

dataGridView1.Source = null;
dataGridView1.Rows.Add("1");

but it clears my previous data in table. How to do it, to add new row without deleting previous data?

解决方案

When you set the DataSource property to null, you are essentially removing all data from the DataGridView (since it doesn't know what to bind to anymore).

You have two options here. The first is to update the underlying data source. Let's assume that it's a DataTable. In this case, you'd do something like:

DataTable dt = dataGridView1.Source as DataTable;
dt.Rows.Add(new object[] { ... });

And then the DataGridView will pick up on the changes (note that if you are not binding to something that doesn't implement the INotifyCollectionChanged interface, you'll have to call the ResetBindings method to get the grid to refresh).

The other option is to let the DataGridView manage the rows. You can do this by manually adding each item using the Add method on the DataGridViewRowCollection returned by the Rows property:

foreach (var item in source)
{
    dataGridView1.Rows.Add("1", "2", "3", ...);
}

I wouldn't say the second solution is optimal, but it will work.

Finally, assuming you are binding to a DataTable (or some other materialization of the data from an underlying data source), this doesn't do anything about to updating underlying data source (that would be a separate question).

这篇关于如何添加新行到datagridview?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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