By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,950 Members | 1,035 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,950 IT Pros & Developers. It's quick & easy.

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

P: 1
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!


Expand|Select|Wrap|Line Numbers
  1. Imports System.Data.SqlClient
  2.  
  3. Public Class Form1
  4. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  5. Dim cn As New SqlConnection("Data Source=.\SQLEXPRESS;Initial Catalog=drpractice;Integrated Security=True")
  6. Dim da As New SqlDataAdapter
  7. Dim ds As New DataSet
  8. Try
  9. cn.Open()
  10. da.SelectCommand = New SqlCommand("SELECT * FROM [emp_tbl]", cn)
  11. da.Fill(ds)
  12. Dim dt As New DataTable
  13. dt = ds.Tables("emp_tbl")
  14. Dim dr As DataRow = dt.NewRow()
  15. dr.Item("emp_id") = TextBox1.Text.Trim
  16. dr.Item("emp_name") = TextBox2.Text.Trim
  17. dr.Item("salary") = TextBox3.Text.Trim
  18. dr.Item("age") = TextBox4.Text.Trim
  19. dr.Item("emp_group") = TextBox5.Text.Trim
  20. dt.Rows.Add(dr)
  21. da.Update(ds)
  22. MsgBox("Record Successfully Inserted")
  23. Catch ex As Exception
  24. MsgBox(ex.Message)
  25. End Try
  26. End Sub
  27. End Class 
Feb 11 '13 #1
Share this Question
Share on Google+
1 Reply


zmbd
Expert Mod 5K+
P: 5,371
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_GUIDELINES: Please Read Carefully Before Posting to a Forum.
Feb 11 '13 #2

Post your reply

Sign in to post your reply or Sign up for a free account.