how to update row in DataGridView?

孤人 提交于 2019-12-20 07:40:45

问题


I have a DataGridView that is populated from a DataSet.

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

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


回答1:


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




回答2:


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);



回答3:


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.




回答4:


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);



回答5:


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.



来源:https://stackoverflow.com/questions/2135737/how-to-update-row-in-datagridview

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!