简体   繁体   English

C#WinForms:向数据绑定的DataGridView添加行

[英]C# WinForms: Adding row to a DataGridView which is Data bound

I have a Datagridview containing two buttons, an AddEntry button and an EditEntry button in a form. 我有一个Datagridview包含两个按钮,窗体中的一个AddEntry按钮和一个EditEntry按钮。 Whenever the form is loaded, data from an excel sheet will be loaded to the gridview. 每当加载表单时,Excel工作表中的数据都将加载到gridview。

I don't have any problem loading data from excel sheet to gridview. 我没有任何问题将数据从Excel工作表加载到gridview。 AddEntry button will redirect me to another form which has some textboxes to add entry. AddEntry按钮会将我重定向到另一个表单,该表单具有一些用于添加条目的文本框。

However, when I try to add a new entry to the gridview by clicking the AddEntry button, I get this error: "ROWS CANNOT BE PROGRAMMATICALLY ADDED TO THE ROW COLLECTION WHICH IS CONTROL BOUND/DATA BOUND". 但是,当我尝试通过单击AddEntry按钮将新条目添加到gridview时,出现以下错误:“行不能通过编程方式添加到控制绑定/数据绑定的行集合中”。

Here is my code-behind AddEntry Button: 这是我在AddEntry按钮后面的代码:

 private void AddEntry_Click(object sender,eventargs e)
 {
     gridview.Rows.Add(_sno.Text,_date.Text,_category.Text);
 }

Constructor in the form which has textboxes to add data: 具有文本框以添加数据的形式的构造方法:

DataGridView gridview;
public FinanceEntries_Open(DataGridView _grid,string filename)
{
    InitializeComponent();
    label2.Text = filename;
    gridview = _grid;
}

If you are using the DataSource property of the DataGridView to bind to data you cannot explicitly add rows directly to the DataGridView . 如果您使用DataGridViewDataSource属性绑定到数据,则不能显式直接将行添加到DataGridView You must instead add rows directy to your data source. 相反,您必须直接向数据源添加行。

Instead, you can add this new row to the DataSet or DataTable which is bound to the DataGridView. 而是可以将此新行添加到绑定到DataGridView的DataSet或DataTable中。

You can use DataTable.NewRow method to add a new row to the bound data and refresh the GridView. 您可以使用DataTable.NewRow方法将新行添加到绑定的数据并刷新GridView。

If you are binding a DataTable 如果要绑定DataTable

DataTable dataTable = new DataTable();
DataRow newRow = dataTable.NewRow();

// add new data to this newRow

dataTable.Rows.Add(newRow);

If you are using a List 如果您使用List

List<YOUR_DATA_LIST> myData = new List<YOUR_DATA_LIST>();

//Add new YOUR_DATA_LIST object to the list
myData.Add(new YOUR_DATA_LIST());

//Now Refresh / Reset the Datasource
gridView.DataSource = null;
gridView.DataSource = myData;

Since you are using binding, you need to add your object to the underlying collection and not the data grid view directly. 由于使用绑定,因此需要将对象添加到基础集合中,而不是直接添加到数据网格视图中。 If you are using a list or a data table, add the new object to this collection. 如果使用列表或数据表,则将新对象添加到此集合中。 By virtue of the binding it will show in your data grid view. 通过绑定,它将显示在您的数据网格视图中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM