使用C#DataGridView更新SQL表?

时间:2013-04-01 12:48:53

标签: c# sql sql-server datagridview sql-server-ce

我正在一个包含DataGridView的程序中创建一个表单。有一些特定的按钮可以从数据库中查看不同的表,这些按钮工作正常。但是,我还希望能够编辑表的内容并将更改发送回数据库。在“编辑预订”按钮上,按下DataGridView的数据源设置为连接到SQL语句的数据适配器:

SELECT * FROM bookings

这很好用;输出显示表格,我有以下几行:

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

允许在数据网格中进行编辑。我遇到的问题是更新放入数据网格的任何输入。如果可能的话我想在“更新按钮”按下或按下其他按钮时更新表,但我尝试使用SqlCommandBuilder生成插入和更新命令,然后调用DataAdapter.Update()但我想我是做错了。任何人都可以告诉我如何实现我想要实现的目标吗?

提前致谢, 迈克尔。

1 个答案:

答案 0 :(得分:3)

在您的更新按钮中:

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