What is the use of the CommandBuilder class ?

 Posted by Bharathi Cherukuri on 5/21/2012 | Category: ADO.NET Interview questions | Views: 14713 | Points: 40

The CommandBuilder class is used to automatically update a database according to the changes made in a DataSet.

This class automatically registers itself as an event listener to the RowUpdating event. Whenever data inside a row changes, the object of the CommandBuilder class automatically generates a SQL statement and uses the SelectCommand property to commit the changes made in DataSet.

For Example, OLEDB provider in .NET Framework has the OleDbCommandBuiider class; whereas, the SQL provider has the SqlCommandBuilder class.

Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Posted by: Akiii on: 5/23/2012 | Points: 10
Good explanation. Can you provide a sample code ?

Thanks and Regards
Posted by: Bharathi Cherukuri on: 5/24/2012 | Points: 10
Hi Akiii,

Here is the sample code for CommandBuilder class.


public static DataSet SelectSqlRows(string connectionString,

string queryString, string tableName)
using (SqlConnection connection = new SqlConnection(connectionString))
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(queryString, connection);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);


DataSet dataSet = new DataSet();
adapter.Fill(dataSet, tableName);

//code to modify data in DataSet here


//Without the SqlCommandBuilder this line would fail
adapter.Update(dataSet, tableName);

return dataSet;


Login to post response