Gold
Gold

Reputation: 62424

how to update row in DataGridView?

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?

Upvotes: 0

Views: 33904

Answers (5)

Sarvar Nishonboyev
Sarvar Nishonboyev

Reputation: 13080

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.

Upvotes: 0

BSP11
BSP11

Reputation: 11

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

Upvotes: 1

BSP11
BSP11

Reputation: 11

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

Upvotes: 0

Andy West
Andy West

Reputation: 12499

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.

Upvotes: 4

User1
User1

Reputation: 41163

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.

Upvotes: 0

Related Questions