Automatic Generated DataGrid Commands


Description 

This article illustrates how to update, insert, and delete in the windows DataGrid control by using automatic generated commands. There are two main functions which handle retrieving  and manipulating data. To manipulate data in DataGrid, you have to create commands for them.

MSDN documentation states that If your DataTable maps to or is generated from a single database table, you can take advantage of the CommandBuilder object to automatically generate the DeleteCommand, InsertCommand, and UpdateCommand of the DataAdapter. This simplifies and reduces the code required to perform INSERT, UPDATE, and DELETE operations.The SelectCommand must also return at least one primary key or unique column. If none are present, an InvalidOperation exception is generated, and the commands are not generated.

The code is self explanatory, if you just review the code line by line, you will not have any problem to understand how it is done.

Source Code:

private void GridBind()
{
///connection string which will be different in your computer
StringConnStr="server=(local)\\NetSDK;uid=northwind;pwd=northwind;database=northwind";
SqlConnection myConnection= new SqlConnection(ConnStr);
///instantiate SqlDataAdapter to create DataSet
CustomerAdapter = new SqlDataAdapter("select * from customers",myConnection);
/// the following is for creating automatic command builder
CustomerCmdBuilder = new SqlCommandBuilder(CustomerAdapter);
///fill the dataset
CustomerAdapter.Fill(CustomerDataSet, "Customers");
///set the dataset as a datasource for windows datagrid
dataGrid1.SetDataBinding(CustomerDataSet,"Customers");
}
private void btnSave_Click(object sender, System.EventArgs e)
{
try
{
///the following statement
///inserts
///updates
///deletes for you
/// Without the SqlCommandBuilder, this line would fail.
CustomerAdapter.Update(CustomerDataSet,"Customers");
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}


Similar Articles