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

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

问题描述

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

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...

我尝试:

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?

推荐答案

当您设置的 数据源属性,你是除去基本上的所有的从 DataGridView的 (因为它不知道该怎么绑定了)。

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[] { ... });

和则 DataGridView的将回暖更改(注意,如果你不具有约束力的东西,没有实现 INotifyCollectionChanged 接口,你必须调用的 ResetBindings 方法得到电网刷新)。

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).

另一种选择是让 DataGridView的管理行。您可以通过使用 添加<手动添加的每个项目/ code做到这一点>在 href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewrowcollection.aspx\"> DataGridViewRowCollection 属性:

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", ...);
}



我不会说的第二种解决方案是的优化,但它会奏效。

最后,假设你绑定到数据表(或其他一些物化从底层数据源中的数据),这并不做任何事情,以更新基础数据源(这将是一个单独的问题)。

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天全站免登陆