Database Updates From DatagridView


Introduction

A DataGridView control can be used to display data from a database. A table can be displayed from a database in a DataGridView, using the DataAdapter class and data logic. You can easily update a database from a DataGridView.

DataGridView1.gif

Step 1

Create a Windows Forms Application Project, and place a DataGridView on the form.
 
Step 2

Click on the pin button on right-up side of DataGridView and click add project DataSource. And follow these simple steps.

  • Choose DataSourceType Database
  • New Connection, Make Connection
  • Select Table and Column names
  • Finish

DataGridView2.gif

DataGridView3.gif

Step 3

Your DataSet now has been created. You can see it from the Solution Explorer.

DataGridView4.gif

Step 4

See the properties of the Adapter on DataSet, whether it has a query for updating or not. If not then add an update query.

datagrideviewdata.gif

Step 5

A line is automatically generated, when you bind the DataGridView to the dataset. As:

private void testGrid_Load(object sender, EventArgs e)
{
     
// TODO: This line of code loads data into the 'gridTestDataSet.Emp' table. You can move, or remove it, as needed.
     this.empTableAdapter.Fill(this.gridTestDataSet.Emp); 
}

On Click Event of Update button

private void button3_Click(object sender, EventArgs e)
{
     
//Update button update dataset after insertion,upadtion or deletion
     DialogResult dr = MessageBox.Show("Are you sure to save Changes", "Message", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information);
     if (dr == DialogResult.Yes)
     {
          this.empTableAdapter.Update(gridTestDataSet.Emp);
          dataGridView1.Refresh();
          MessageBox.Show("Record Updated");
     }
}


Points of Interest

You can insert a row and click the update button; a row in the database will be inserted.

If you update any cell and click the update button, then the database will be updated.

To delete, select the rows and then press the Delete key and click the update button; the rows will be deleted. All your insertions, updates, and deletions will be effected by the single button.


Similar Articles