简体   繁体   中英

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. Whenever the form is loaded, data from an excel sheet will be loaded to the gridview.

I don't have any problem loading data from excel sheet to gridview. AddEntry button will redirect me to another form which has some textboxes to add entry.

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

Here is my code-behind AddEntry Button:

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

You can use DataTable.NewRow method to add a new row to the bound data and refresh the GridView.

If you are binding a 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<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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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