Results 1 to 5 of 5

Thread: How to Insert Record to Related Table in an ADO.NET Dataset?

Threaded View

  1. #1

    Thread Starter
    New Member
    Join Date
    Feb 2012
    Posts
    4

    Thumbs up How to Insert Record to Related Table in an ADO.NET Dataset?

    Hi everybody,

    I've been having a problem adding a record to a Child table (Products). The Parent table (Categories) has already data in it. The two tables have one-to-many relationship.
    The problem in the code starts when I want to insert a new record to child table (Products) as below:

    Code:
    Dim objConn As SqlConnection
    Dim da1 As SqlDataAdapter
    Dim da2 As SqlDataAdapter
    Dim ds As New DataSet
    objConn = New SqlConnection(ConfigurationSettings.Appsettings("NorthwindConnection"))
    da1 = New SqlDataAdapter("SELECT * FROM Categories", objConn)
    da2 = New SqlDataAdapter("SELECT * FROM Products", objConn)
    Try
    
    objConn.Open()
    ' Add the tables to the DataSet
     da1.Fill( ds,"Categories")
    da2.Fill(ds, "Products")
    'Create the Data Relationship
    ds.Relations.Add("ProdCat",ds.Tables("Categories").Columns("CategoryID"), _
    ds.Tables("Products").Columns("CategoryID"))
     ' Add new record to the child table (Products )
    Dim cb As New OleDb.OleDbCommandBuilder(da)
    Dim Row1 As DataRow = ds.Tables("Products").Addnew()
    Row1("ProductName") = trim(Textbox2.Text)
    Row1("ProductDescription") = trim(Textbox3.Text)
    ds.Tables("Products").Rows.Add(Row1)
    da2.Update(ds, "Products")
    
    Catch exc As SqlException
    MessageBox.Show(ex.Message)
    Finally
    objConn.Dispose()
    End Try
    I read the following article, but I couldn't figure out how to insert record to a child table.

    http://msdn.microsoft.com/en-us/libr...=vs.71%29.aspx

    I would really appreciate if someone could help me out, or if there is any other way to solve this problem maybe by using a completly different code!
    Thanks in advance
    Last edited by HardWorker; Feb 18th, 2012 at 01:16 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width