I am trying to save checked items from a checkedlistbox to my SQL database and i am filling my checkedlistbox from the same SQL database,So far i am able to get the text of checked item from the checkedlistbox and i saved it in a string then i used a label to display if i am getting the text of checked item or not and its working but when i try to insert the checked data in database i get a error "Connection property has not been initialized." on ExecuteNonQuery() method.
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim da As New SqlDataAdapter
Dim dt As New DataTable
Dim connectionString As String = "Server=DESKTOP-V12PTAV ;Database=test ;User Id=sa ;Password=wills8877"
Using conn As New SqlConnection(connectionString)
conn.ConnectionString = connectionString
conn.Open()
Dim str As String
str = "Select sem1 From sem"
da = New SqlDataAdapter(str, conn)
dt = New DataTable
da.Fill(dt)
CheckedListBox1.DataSource = dt
CheckedListBox1.DisplayMember = "sem1"
conn.Close()
End Using
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim str As String
Dim cmd As New SqlCommand
Dim sql As String
Dim connectionString As String = "Server=DESKTOP-V12PTAV ;Database=test ;User Id=sa ;Password=wills8877"
Using conn As New SqlConnection(connectionString)
conn.Open()
Dim itemChecked As Object
For Each itemChecked In CheckedListBox1.CheckedItems
str = itemChecked.item("sem1").ToString
Label1.Text = str
sql = "insert into pretab(pre) values('" + str + "')"
cmd.ExecuteNonQuery()
Next
conn.Close()
End Using
End Sub
End Class
This error
The problem maybe arised from your query syntax. Try this:
sql = "insert into pretab(pre) values(#str)"
cmd.Parameters.AddWithValue("#str", str)
cmd.ExecuteNonQuery()
OOPS.. I just realised that you forgot to assign your command with connection. So, please try to add the following statement:
cmd = New SqlCommand(sql, conn)
befor execution your command. So the final code should look like this:
sql = "insert into pretab(pre) values(#str)"
cmd = New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("#str", str)
cmd.ExecuteNonQuery()
First off I would do data operations in a class e.g. (note I focus on inserts). You need to change server and catalog to your server and catalog on SQL-Server.
Imports System.Data.SqlClient
Public Class Operations
Private Server As String = "KARENS-PC"
Private Catalog As String = "CheckedListBoxDatabase"
Private ConnectionString As String = ""
Public Sub New()
ConnectionString = $"Data Source={Server};Initial Catalog={Catalog};Integrated Security=True"
End Sub
Public Function Read() As DataTable
' read rows for checked listbox here
End Function
Public Sub Insert(ByVal sender As List(Of String))
Using cn As SqlConnection = New SqlConnection With {.ConnectionString = ConnectionString}
Using cmd As SqlCommand = New SqlCommand With {.Connection = cn, .CommandText = "insert into pretab(pre) values (#pre)"}
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#pre", .SqlDbType = SqlDbType.NVarChar})
cn.Open()
For Each item In sender
cmd.Parameters("#pre").Value = item
cmd.ExecuteNonQuery()
Next
End Using
End Using
End Sub
End Class
Form code
Public Class Form1
Private ops As New Operations
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Result = CheckedListBox1.Items.OfType(Of String).Where(Function(item, index) CheckedListBox1.GetItemChecked(index)).ToList
ops.Insert(Result)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
CheckedListBox1.DataSource = ops.Read
CheckedListBox1.DisplayMember = "sem1"
End Sub
End Class
It appears that you did not provide the connection to the command. Your code was button click
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim str As String
Dim cmd As New SqlCommand
Dim sql As String
Dim connectionString As String = "Server=DESKTOP-V12PTAV ;Database=test ;User Id=sa ;Password=wills8877"
Using conn As New SqlConnection(connectionString)
conn.Open()
Dim itemChecked As Object
For Each itemChecked In CheckedListBox1.CheckedItems
str = itemChecked.item("sem1").ToString
Label1.Text = str
sql = "insert into pretab(pre) values('" + str + "')"
cmd.ExecuteNonQuery()
Next
conn.Close()
End Using
End Sub
What you need to do is before cmd.ExecuteNonQuery() you need to provide it a connection cmd.connection = connectionString
this will remove the cmd.ExecuteNonQuery() error.
So I have this code in my form but when I try to click the search button to search for a name and show it into my datagrid view using the details from my sql database, it brings nothing. Just blank datagrid.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
Dim tblClientDetails As New DataTable
If CON.State = ConnectionState.Closed Then
CON.Open()
End If
With cmd
.Connection = CON
.CommandText = "select * from tblClientDetails where name = #name"
.CommandType = CommandType.Text
.Parameters.AddWithValue("#name", TextBox1.Text)
dr = .ExecuteReader
End With
While (dr.Read)
DataGridView1.DataSource = tblClientDetails
End While
My data in sql which i want to be shown in my datagrid below after searching from a textbox
http://i.stack.imgur.com/3J9lh.png
My form's data grid looks like this;
http://i.stack.imgur.com/QxmF5.png
try this..
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim sqlCmd As New SqlCommand()
If CON.State = ConnectionState.Closed Then
CON.Open()
End If
sqlCmd.CommandText = "select * from tblClientDetails where name = #name"
sqlCmd.Connection = CON
sqlCmd.Parameters.AddWithValue("#name", TextBox1.Text)
Dim dr As SqlDataReader = sqlCmd.ExecuteReader()
Dim tblClientDetails As New DataTable()
tblClientDetails.Load(dr)
DataGridView1.DataSource = objDataTable
DataGridView1.DataBind()
CON.Close()
End Sub
Sample example to load a data reader to your data table and then data table to your grid is shown below.
Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs)
If Not Page.IsPostBack Then
Dim MyConnection As SqlConnection
Dim MyCommand As SqlCommand
Dim MyDataTable As DataTable
Dim MyReader As SqlDataReader
Dim CityParam As SqlParameter
MyConnection = New SqlConnection()
MyConnection.ConnectionString = ConfigurationManager.ConnectionStrings("DSN_Northwind").ConnectionString
MyCommand = New SqlCommand()
MyCommand.CommandText = " SELECT * FROM CUSTOMERS WHERE CITY = #CITY "
MyCommand.CommandType = CommandType.Text
MyCommand.Connection = MyConnection
CityParam = New SqlParameter()
CityParam.ParameterName = "#CITY"
CityParam.SqlDbType = SqlDbType.VarChar
CityParam.Size = 15
CityParam.Direction = ParameterDirection.Input
CityParam.Value = "London"
MyCommand.Parameters.Add(CityParam)
MyCommand.Connection.Open()
MyReader = MyCommand.ExecuteReader(CommandBehavior.CloseConnection)
MyDataTable = New DataTable()
MyDataTable.Load(MyReader)
gvCustomers.DataSource = MyDataTable
gvCustomers.DataBind()
MyDataTable.Dispose()
MyCommand.Dispose()
MyConnection.Dispose()
End If
End Sub
Source available here
I'm trying to refill my DataGridView after a filter selection in a combobox.
Here is my code where I try...at this moment the code is clearing the DataGridview and just fill only on row with only 1 cell..KlantID = 7
Any idea?
Private Sub ComboBox1_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox1.SelectionChangeCommitted
klantid = ComboBox1.SelectedValue
Dim myConnection As OleDbConnection
Dim DBpath As String = "C:\Facturatie\CharelIjs.accdb"
Dim sConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & DBpath & ";Persist Security Info=True"
myConnection = New OleDbConnection(sConnectionString)
myConnection.Open()
Dim SQLstr As String
SQLstr = "SELECT * FROM tblKlant WHERE KlantID = #klantid"
Dim cmd As New OleDbCommand(SQLstr, myConnection)
Dim da As New OleDbDataAdapter(cmd)
Dim ds As New DataSet()
cmd.Parameters.Add("#klantid", OleDbType.VarChar)
cmd.Parameters(0).Value = klantid
Try
da.Fill(ds, "tblKlant")
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox("Can't load Web page" & vbCrLf & ex.Message)
Return
End Try
DataGridView1.DataSource = ds
DataGridView1.DataMember = "tblKlant"
DataGridView1.Refresh()
End Sub
Why are you populating records on every combobox_SelectionChange event execution. Try to filter your data only instead of query execution.
And, better to use SelectedValueChanged event instead of SelectionChange.
Private Sub form_Load(sender As Object, e As EventArgs) Handles Me.Load
//Fill your data here with DataView
Dim myConnection As OleDbConnection
Dim DBpath As String = "C:\Facturatie\CharelIjs.accdb"
Dim sConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & DBpath & ";Persist Security Info=True"
myConnection = New OleDbConnection(sConnectionString)
myConnection.Open()
Dim cmd As New OleDbCommand("SELECT * FROM tblKlant", myConnection)
Dim da As New OleDbDataAdapter(cmd)
Dim dt As New DataTable() 'Dont use dataset if your are not relating more than one tables
cmd.Parameters.Add("#klantid", OleDbType.VarChar)
cmd.Parameters(0).Value = klantid
Try
da.Fill(dt)
dt.TableName = "tblKlant"
cmd.ExecuteNonQuery()
DataGridView1.DataSource = dt.DefaultView
DataGridView1.DataMember = "tblKlant"
Catch ex As Exception
MsgBox("Can't load Web page" & vbCrLf & ex.Message)
Return
End Try
End Sub
Private Sub combobox_SelectedValueChanged(sender As Object, e As EventArgs) Handles combobox.SelectedValueChanged
IF combobox.SelectedValue IsNot Nothing Then
Dim dv As DataView = DirectCast(DataGridView1.DataSource, DataView)
dv.RowFilter = "KlantID=" + combobox.SelectedValue.ToString()
Else
dv.RowFilter = vbNullString
End IF
End Sub
Here is a code that retrieve values from the database, but my problem is that it throws out an exception saying "InvalidCastException was unhandled specified cast is not valid". I am now confused what went wrong, The code and the table stated below.
Here is the code:
Public connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source =" & Application.StartupPath &
"\TestData.accdb; Persist Security info = false"
Public Conn As New OleDbConnection
Private Sub TestForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Loard
Conn.ConnectionString = connstring
Conn.Open()
LoadValue( )
End Sub
Private Sub LoadValue( )
Dim i As Integer
Dim cmd As OleDbCommand = New OleDbCommand
With cmd
.CommandText = "SELECT MAX(Guard_ID) FROM Guard"
.CommandType = CommandType.Text
.Connection = Conn
.ExecuteNonQuery()
Dim reader As OleDbDataReader = cmd.ExecuteReader
If reader.Read Then
TextBox1.Text = reader.GetString(0)
i = TextBox1.Text + 1
TextBox1.Text = i
reader.Close()
End If
End With
End Sub
The table reference:
Exception Error:
I am really confused now on why the code does not work, any help and advice will be gladly accepted. Thanks in advance.
try this,
Private Sub LoadValue()
Dim i As Integer
Dim cmd As OleDbCommand = New OleDbCommand
With cmd
.CommandText = "SELECT MAX(Guard_ID) FROM Guard"
.CommandType = CommandType.Text
.Connection = Conn
.ExecuteNonQuery()
Dim reader As OleDbDataReader = cmd.ExecuteReader
If reader.Read Then
Dim tmpVal As Object = reader.Item(0)
TextBox1.Text = IIf(IsDBNull(tmpVal), "0", tmpVal.ToString())
i = CInt(TextBox1.Text) + 1
TextBox1.Text = i.ToString()
reader.Close()
End If
End With
End Sub
Getting an error here not sure why its not opening the connection. Hoping someone can help me.
Protected Sub Btn_Submit_Click(ByVal sender As System.Object, e As System.EventArgs) Handles Btn_Submit.Click
Dim Sqlstr As String
Dim con As SqlConnection
Dim connectionString As String = "Data Source=DB\TEST;Initial Catalog=Orders;Integrated Security=True"
Dim cmdInsert As New SqlCommand(Sqlstr, con)
Sqlstr = "insert into customers(FirstName,LastName,Email,Phone,Address,City,State,Zip) values (#FirstName,#LastName,#Email,#Phone,#Address,#City,#State,#Zip)"
Try
Using connection As New SqlConnection(connectionString)
connection.Open()
cmdInsert.Parameters.Add("#FirstName", Data.SqlDbType.NVarChar).Value = FirstName.Text()
cmdInsert.Parameters.Add("#LastName", Data.SqlDbType.NVarChar).Value = LastName.Text
cmdInsert.Parameters.Add("#Email", Data.SqlDbType.NVarChar).Value = Email.Text
cmdInsert.Parameters.Add("#Phone", Data.SqlDbType.NChar).Value = Phone.Text
cmdInsert.Parameters.Add("#Address", Data.SqlDbType.NVarChar).Value = Address.Text
cmdInsert.Parameters.Add("#City", Data.SqlDbType.NVarChar).Value = City.Text
cmdInsert.Parameters.Add("#State", Data.SqlDbType.NVarChar).Value = State.Text
cmdInsert.Parameters.Add("#Zip", Data.SqlDbType.NChar).Value = Zip.Text
cmdInsert.ExecuteNonQuery()
connection.Close()
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
You have two SqlConnection objects - one in Dim con As SqlConnection and then another in your using statement. Create the SqlCommand after the using statement and pass the connection in to the constructor.
You have the wrong scope -- you're instantiating your SqlCommand before instantiating and opening the actual SQL connection you're trying to use to execute the command.
I believe this is what will fix your code (I moved the insert call into the using scope):
Protected Sub Btn_Submit_Click(ByVal sender As System.Object, e As System.EventArgs) Handles Btn_Submit.Click
Dim Sqlstr As String
Dim connectionString As String = "Data Source=DB\TEST;Initial Catalog=Orders;Integrated Security=True"
Sqlstr = "insert into customers(FirstName,LastName,Email,Phone,Address,City,State,Zip) values (#FirstName,#LastName,#Email,#Phone,#Address,#City,#State,#Zip)"
Try
Using connection As New SqlConnection(connectionString)
connection.Open()
Dim cmdInsert As New SqlCommand(Sqlstr, connection) <----- **** Moved this here, changed the connection
cmdInsert.Parameters.Add("#FirstName", Data.SqlDbType.NVarChar).Value = FirstName.Text()
cmdInsert.Parameters.Add("#LastName", Data.SqlDbType.NVarChar).Value = LastName.Text
cmdInsert.Parameters.Add("#Email", Data.SqlDbType.NVarChar).Value = Email.Text
cmdInsert.Parameters.Add("#Phone", Data.SqlDbType.NChar).Value = Phone.Text
cmdInsert.Parameters.Add("#Address", Data.SqlDbType.NVarChar).Value = Address.Text
cmdInsert.Parameters.Add("#City", Data.SqlDbType.NVarChar).Value = City.Text
cmdInsert.Parameters.Add("#State", Data.SqlDbType.NVarChar).Value = State.Text
cmdInsert.Parameters.Add("#Zip", Data.SqlDbType.NChar).Value = Zip.Text
cmdInsert.ExecuteNonQuery()
connection.Close()
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
Protected Sub Btn_Submit_Click(ByVal sender As System.Object, e As System.EventArgs) Handles Btn_Submit.Click
Dim Sqlstr As String
' =================================================
' This is a declaration, not an instantiation
' =================================================
Dim con As SqlConnection
Dim connectionString As String = "Data Source=DB\TEST;Initial Catalog=Orders;Integrated Security=True"
' =================================================
' con is Nothing here
' =================================================
Dim cmdInsert As New SqlCommand(Sqlstr, con)
Sqlstr = "insert into customers(FirstName,LastName,Email,Phone,Address,City,State,Zip) values (#FirstName,#LastName,#Email,#Phone,#Address,#City,#State,#Zip)"
Try
' =================================================
' connection is not what you passed to cmdInsert
' =================================================
Using connection As New SqlConnection(connectionString)
connection.Open()
Connection Sting Property Error always occur when the connection is not declared/renewed
the solution is simple
dim con as new SqlConnection
con.connectionString = "Provide your SQL connection"
con.open
'write code or action you want to perform
con.close
Hope it helps.