DataBase Updation With DataGridView in simple steps
Here is a step by step process to update database through datagridview in Windows applications
Introduction
DataGridView
control is used for displaying data from database. Display a table from the database on the DataGridView
, using DataAdapter
and data logic. You can update the database from datagridView
in a few simple steps.
Brief about DataAdapter
: DataAdapter
works as a bridge between DataSource
and DataSet
to save and fetch data.The Fill()
method is used to load data in DataSet
. A DataAdapter
has various queries (In Properties) like:
-
SelectCommand
-
InsertCommand
-
DeleteCommand
UpdateCommand
Update()
method is used for making changes in database.OleDbDataAdapter
is a sealed class that inherits abstract DbDataAdapter
class and implements IDbDataAdapter
, IDataAdapter
, ICloneable
interfaces. Here is an example of
OledbDataAdapter
:Example of
DataAdapter
: Step 1
Create a Windows Application Project, and take a
gridview
on Windows form.Step 2
Click on pin button on right-up side of
datagridview
and click add project DataSource
and follow the simple steps:->Choose DataSourceType database
->New Connection,
->make Connection
->Select Table and Column names
->Finish
Step 3
Your
dataSet
has now been created. You can see it from Solution explorer.When you create
DataSet EmpTableAdapter
and when you check the properties of this adapter, you will find Insert
, Delete
, Update
, Select
queries that are automatically generated as in Step 4. Step 4
See the properties of
Adapter
on DataSet
, whether it has query for Update
or not. If not, add update
query.Step 5
A line is auto generated, when you bind
datagrid
to 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);
}
The Fill()
method retrieves rows from the data source using the SELECT
statement specified by an associated SelectCommand
property of DataAdapter
. On
Click
event of Update
button:private void button3_Click(object sender, EventArgs e)
{
//Update button update dataset after insertion, updation 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 update button, row in database will be inserted.
- If you update any cell and click update button, the database will be updated.
- To delete, select rows and press Delete key and click update button, rows will be deleted.