Automatic Generated DataGrid Commands
This article illustrates how to update, insert, and delete in the windows DataGrid control by using automatic generated commands.
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.
private void GridBind()
///connection string which will be different in your computer
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
///set the dataset as a datasource for windows datagrid
private void btnSave_Click(object sender, System.EventArgs e)
///the following statement
///deletes for you
/// Without the SqlCommandBuilder, this line would fail.