简体   繁体   中英

Using a C# DataGridView to update SQL tables?

I'm making a form in a program that contains a DataGridView. There are specific buttons for viewing different tables from the database, which work fine. However, I also want to be able to edit the contents of the tables and send the changes back to the database. On the 'Edit Bookings' button press, the DataGridView's data source is set to a data adapter connected to the SQL statement:

SELECT * FROM bookings

This works fine; the output shows the table, and I have the lines:

adminDataGrid.AllowUserToDeleteRows = true;
adminDataGrid.AllowUserToAddRows = true;

to allow editing in the data grid. The issue I am having is with updating any input put into the data grid. If possible I would like to update the table either on a 'Update button' press or when a different button is pressed, but I have tried using SqlCommandBuilder to generate insert and update commands, then calling DataAdapter.Update() but I think I am doing something quite wrong. Can anybody run me through how I would achieve what I'm looking to achieve?

Thanks in advance, Michael.

In your update button:

int id; 
string name;
string address;  

for (int i = 0; i <= adminDataGrid.Rows.Count-1; i++)
{
    id = int.Parse(adminDataGrid.Rows[i].Cells["ID"].Value);
    name = adminDataGrid.Rows[i].Cells["NAME"].Value.ToString();
    address = adminDataGrid.Rows[i].Cells["Address"].Value.ToString();
// now write the C# code to update your table using id, name and address. in first cycle of the for loop the table will update with first row data of your adminDataGrid. 
}

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