Need Help with SQL Connection (VB.net)

  • Thread starter Thread starter badgerdds
  • Start date Start date
B

badgerdds

Guest
Hi All

Hoping someone can help me, hopefully an easy fix!

I'm very new to VB/Visual Studio, I'm basically teaching myself how - I've got a Windows Form I have built, very simple, just a First Name and Last Name field and I'm trying to work out how to get it to wrtie whatever value is entered into those two fields, into my SQL Database - where i have a table called "Users". I have imported the SQL database into the project so i'm sure thats all working ok - but i just cant seem to get it to execute! i keep getting the below error.

I've sat and read/watched hours of youtube videos and guides on how to get this to work, but i just cant get past this. Please could someone provide some help? My thanks in advance!


System.InvalidOperationException: 'ExecuteNonQuery: Connection property has not been initialized.'

This happens on the line:

command.ExecuteNonQuery()


Here is the full code:

Imports System.Data
Imports System.Data.SqlClient

Public Class SQTest

Dim cn As New SqlConnection("Data Source=DESKTOP-94NTTM7\SQLEXPRESS01;Initial Catalog=HATS;Integrated Security=True")


Private Sub SQTest_Load(sender As Object, e As EventArgs) Handles MyBase.Load

End Sub



Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

Dim command As New SqlCommand("insert into Users(First Name,Last Name) value('" & FName.Text & "', '" & Lname.Text & "')")

cn.Open()

command.ExecuteNonQuery()

cn.Close()




End Sub


End Class

Continue reading...
 
Back
Top