C# 如何更新DataGridView中的行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2135737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 23:48:10  来源:igfitidea点击:

how to update row in DataGridView?

c#ado.net

提问by Gold

I have a DataGridViewthat is populated from a DataSet.

我有一个DataGridView从数据集填充的。

How can I change any cell in the DataGridView, and have this change the DataSet too (and the Database).

我如何更改DataGridView.

Is there a sample program for this (in C#) that I can learn from?

是否有我可以学习的示例程序(在 C# 中)?

采纳答案by Andy West

Here is an articlewith clear explanations, screenshots, and code that demonstrates how to use the DataGridView. The data binding sections should be of particular interest.

这是一篇带有清晰解释、屏幕截图和代码的文章,演示了如何使用 DataGridView。数据绑定部分应该特别有趣。

回答by User1

If you want a program to change the contents of the DataGridView, just change the underlying Dataset. The DataSet has methods to commit those changes to the Database as well.

如果希望程序更改DataGridView 的内容,只需更改底层Dataset。DataSet 也有将这些更改提交到数据库的方法。

回答by BSP11

DataRowView drv = dataGridView1.CurrentRow.DataBoundItem as DataRowView;
DataRow[] rowsToUpdate = new DataRow[] { drv.Row };

SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Categories", con);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
adapter.Update(rowsToUpdate);

回答by BSP11

DataRowView drv = dataGridView1.CurrentRow.DataBoundItem as DataRowView;
DataRow[] rowsToUpdate = new DataRow[] { drv.Row };

SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Categories", con);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
adapter.Update(rowsToUpdate);

回答by Sarvar Nishonboev

I've a app which is connected to access database. In this app, I've done like this:

我有一个连接到访问数据库的应用程序。在这个应用程序中,我是这样做的:

try
{
 con.Open();

 foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)
 {
  OleDbCommand cmd = new OleDbCommand(cmdTxt, con);
  cmd.Parameters.AddWithValue("kurs", c2);
  cmd.Parameters.AddWithValue("ID", item.Cells[0].Value);
  cmd.ExecuteNonQuery();
 }
}
catch (Exception exception)
{
 MessageBox.Show(exception.Message);
}
finally
{
 con.Close();
}

If your database in sql server, then u can use SQlDbCommand class.

如果您的数据库在 sql server 中,那么您可以使用 SQLDbCommand 类。