C# CommandBuilder
The C# CommandBuilder in ADO.NET helps developers generate update, delete., and insert commands on a single database table for a data adapter. Each data provider has a command builder class. The OleDbCommandBuilder, SqlCommonBuilder, and OdbcCommandBuilder classes represent the CommonBuilder object in the OleDb, Sql, and ODBC data providers. These classes also work in a similar fashion. Once you know how to use OleDbCommandBuilder, you can use SqlCommandBuilder and OdbcCommandBuilder in a similar way. I'll use OleDbCommandBuilder class in this example.
Creating a Command Builder
Creating a CommonedBuider object is simple. You pass a DataAdapter as an argument of the CommandBuilder constructor. For example:
- // Create a command builder object
- SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
SqlCommandBuilder Members
The DataAdapter property of a CommonBuilder represents the DataProvider attached to a CommandBuilder object for which automatic SQL statements are generated. The GetDeleteCommand, GetUpdateCommand, and GetInsertCommand methods return the delete, update, and insert commands in the form of a Command object. The RefreshSchema method refreshes the database schema.
Using SqlCommandBuilder
Now you'll see how to use a SqlCommandBuilder in an application. You can use OleDbCommand Builder and ODBCCommandBuilder classes in same way. Listing 5-54 shows how to use SqlCommandBuilder. As you can see, as usual, you create a connection to the database and use it to create the adapter object. The adapter is constructed with the initial query for the Employees table as well as with the database connection.
Next you construct a CommandBuilder by passing a DataAdapter into its constructor. The act of creating the CommandBuilder automatically cause the UPDATE, INSERT, and DELETE commands to be generated for the adapter:
- SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
- // Create a dataset object
- DataSet ds = new DataSet("Employee Set");
- adapter.Fill(ds, "Employees");
Now insert a new DataRow into the DataTable in memory and populates a row with your desired value using DataTable'sAddNew method.
After that you call the DataRowCollection.Add method to add the row to the DataTable:
- // Create a data table object and add a new row
- DataTable EmployeeTable = ds.Tables["Employees"];
- DataRow row = EmployeeTable.NewRow();
- row["firstName"] = "Rodney";
- row["LastName"] = "Dangerfield";
- row["Title"] = "comedian";
- EmployeeTable.Rows.Add(row);

Join the conversation! Your thoughts help the community grow.