Insert a record in sql database using vb.net datatable and datarow features

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • pallabpal87
    New Member
    • Feb 2013
    • 1

    Insert a record in sql database using vb.net datatable and datarow features

    Hi! I am trying to insert a record in sql database using vb.net dataadapter, datatable, and datarow features. I use the following code. But it show me an error.(Object reference not set to an instance of an object).Plz help me!


    Code:
    Imports System.Data.SqlClient
    
    Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim cn As New SqlConnection("Data Source=.\SQLEXPRESS;Initial Catalog=drpractice;Integrated Security=True")
    Dim da As New SqlDataAdapter
    Dim ds As New DataSet
    Try
    cn.Open()
    da.SelectCommand = New SqlCommand("SELECT * FROM [emp_tbl]", cn)
    da.Fill(ds)
    Dim dt As New DataTable
    dt = ds.Tables("emp_tbl")
    Dim dr As DataRow = dt.NewRow()
    dr.Item("emp_id") = TextBox1.Text.Trim
    dr.Item("emp_name") = TextBox2.Text.Trim
    dr.Item("salary") = TextBox3.Text.Trim
    dr.Item("age") = TextBox4.Text.Trim
    dr.Item("emp_group") = TextBox5.Text.Trim
    dt.Rows.Add(dr)
    da.Update(ds)
    MsgBox("Record Successfully Inserted")
    Catch ex As Exception
    MsgBox(ex.Message)
    End Try
    End Sub
    End Class
  • zmbd
    Recognized Expert Moderator Expert
    • Mar 2012
    • 5501

    #2
    By, simply stating that your code "doesn't work," posting a generic/jargon filled error along with code that appears to have had very little if any troubleshooting performed, and expecting someone to help doesn't usually result in much of an answer and may result in your thread being deleted. Instead, please tell us what you were expecting to happen, what actually happened, for each error: the EXACT title, error number, and descriptions that occurred and at what line in your posted code the error occurred. These are the minimum requirements for posting a question of this nature.

    Bytes is not a code nor homework service. Please read the FAQ and posting guidelines before re-posting your question.
    Before Posting (VBA or SQL) Code.
    How to ask "good" questions -- READ BEFORE SUBMITTING A QUESTION!.
    POSTING_GUIDELI NES: Please Read Carefully Before Posting to a Forum.

    Comment

    Working...