ARTICLE

How to insert the data with the CommandBuilder object in ADO.NET

Posted by Rohatash Kumar Articles | ADO.NET in VB.NET February 09, 2011
This article defines that we can insert value in database with out insert command using commandbuilder.
Download Files:
 
Reader Level:

CommandBuilder

CommandBuilder generates insert, update, delete commands for Data adapter based on select command. Similar to other objects, 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.

Creating a CommandBuilder Object

To create a Sqlcommandbuilder we must pass a DataAdapter as an parameter of the commandbuild.

Dim builder As New SqlCommandBuilder(adapter)

Now creating a table in Database and insert the value. like this

create table emp1

(

firstname varchar(20),

lastname varchar(30)

)

go

Insert into emp1 values('Rohatash','kumar')

Insert into emp1 values('Manoj','singh')

go

select * from emp1

OUTPUT

t1.gif

Table1.gif

For example

The below example will insert the employee firstname and last name in the table emp1 from MS SQL server database.

Imports System.Data.SqlClient

Module Module1

    Sub Main()

        Dim con As New SqlConnection("Data Source=.;uid=sa; pwd=123;database=master")

        con.Open()

        Dim adapter As New SqlDataAdapter("SELECT * FROM Emp1 ORDER by firstname", con)

        Dim builder As New SqlCommandBuilder(adapter)

        Dim ds As New DataSet("EmployeeSet")

        adapter.Fill(ds, "Emp1")

        Dim EmployeeTable As DataTable = ds.Tables("Emp1")

        Dim row As DataRow = EmployeeTable.NewRow()

        row("FirstName") = "Bharat"

        row("LastName") = "kumar"

        EmployeeTable.Rows.Add(row)

        adapter.Update(ds, "Emp1")

        Console.WriteLine((row("FirstName").ToString().Trim() & " ") + row("LastName").ToString().Trim() & " Added to Emp1")

    End Sub

End Module

OUTPUT

t2.gif

Now test the table firstname and last name has inserted.

Login to add your contents and source code to this article
share this article :
post comment
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor