There is something definitely missing here; and also a large
SQL Injection Vulnerability
NEVER EVER
should an SQL query be created from piecing together SQL commands and variables
Private Sub btnAddState_Click(sender As Object, e As EventArgs) Handles btnAddState.Click
Try
myCmd.CommandText = "INSERT INTO [dbo].[tblState] ([statename]) VALUES ('" & txtAddState.Text & "')"
myCmd.Connection = myConn
myConn.Open()
The priority item is to add the value stored in the variable to your query correctly. This would be done via an
SqlParameter
. The two lines for this are going to consist of re-defining the query text as well as adding the parameter and value to the command.
Dim query As String = "INSERT INTO [dbo].[tblState] ([statename]) VALUES (@sn)"
myCmd.Parameters.AddWithValue("@sn", txtAddState.Text)
Now onto what is missing... and that would be myCmd
. You never define it as an SqlCommand, you just try to start adjusting the properties.
You can also use the overloads of this object so that the connection and commandtext are done when the variable is declared.
I believe your problem is with
myCmd
. While it is declared at the top of the page; it really is never defined in your code, and until it is defined you cannot get/set any of it's properties. And while you are defining it, you can set the CommandText and Connection properties via an overloaded constructor.
Coupled with the vulnerability fix above, we are now looking at this block of code
Try
Dim query As String = "INSERT INTO [dbo].[tblState] ([statename]) VALUES (@sn)"
myCmd = New SqlCommand(query, myConn)
myCmd.Parameters.AddWithValue("@sn", txtAddState.Text)
myConn.Open()
Sql Paramater reference:
SqlParameter Class (System.Data.SqlClient) | Microsoft Docs[
^]