简体   繁体   English

使用C#DataGridView更新SQL表?

[英]Using a C# DataGridView to update SQL tables?

I'm making a form in a program that contains a DataGridView. 我正在包含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: 在“编辑预订”按钮上,将DataGridView的数据源设置为连接到SQL语句的数据适配器:

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. 如果可能,我想按“更新按钮”或按其他按钮来更新表,但是我尝试使用SqlCommandBuilder生成插入和更新命令,然后调用DataAdapter.Update(),但我想我是做错了什么 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. 
}

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

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