Click here to Skip to main content
15,894,343 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I'm just starting to learn C# and have been playing around with a simple LocalDB and a datagridview showing my data. I have two text boxes and a button for add record, one for save changes to record.

I am struggling to add a row to my datagridview and also struggling to save my changes to the database (I can get them to show on the grid after I filled out my text boxes, but nothing saves to the SQL database.

My dataset is called databaseDataSet, my binding source is called contactsBindingSource and contactsTableAdapter is my table adapter.

What I have tried:

For a new row I have tried:

private void btnNew_Click_(object sender, EventArgs e)
        {
            dataGridView1.Rows.Add();
        }


However, This gives me the following error "Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound." I see now I need to add the row to the table in the data source but how do I do this?



For saving my changes I have tired:

private void btnSave_Click(object sender, EventArgs e)
        {
            
            contactsTableAdapter.Update(databaseDataSet.contacts);
            contactsBindingSource.EndEdit();
            databaseDataSet.AcceptChanges();



This updates the information in my grid to that of the textbox, but doesn't save it to the SQL database? If I close the program it all resets. Can anyone explain what I should be using?

I also tried:

this.Validate();
     this.contactsBindingSource.EndEdit();
     this.contactsTableAdapter.Update(this.databaseDataSet);


This appears to do nothing


Any help appreciated.

Dan
Posted
Updated 7-Mar-21 1:33am
v3

1 solution

Quote:
Add a row to a datagridview that is bound to my datasource

Short answer: you don't.
Your datagridview show records from a datasource, you don't add row to datagridview, you add record to the datasource.
To update a row to datagridview, you update record to the datasource.
 
Share this answer
 
Comments
Dan Coates 7-Mar-21 7:10am    
Have you an example then please?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900