using CheckedListBox in vb.net2008 - vb.net

In vb.net 2008, How To insert Multiple selected Data from Checkedlistbox to Database sql server 2005?
My Code is
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Cn.Close()
Cn.Open()
Try
cmd.CommandText = "insert into Module_Control_tbl (empl_ID,Module_ID) Values('" & ComboBox1.SelectedValue & "','" & CheckedListBox1.SelectedValue & "')"
ComboBox1.Focus()
cmd.Connection = Cn
cmd.ExecuteNonQuery()
MsgBox("Assign Module Successfully to Employee")
Form7_Load(sender, e)
Catch ex As Exception
MsgBox(ex.Message)
MsgBox("contact to Your System Administrator")
End Try
Cn.Close()

You should just iterate through the CheckedItems collection.
Furthermore, you should always use parameters to avoid SQL injection.
Here is an example:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using cn As New SqlConnection("Connection String")
cn.Open()
Dim sb As New StringBuilder
sb.AppendLine("INSERT INTO Module_Control_tbl")
sb.AppendLine("(empl_ID, Module_ID)")
sb.AppendLine("VALUES")
sb.AppendLine("(#empl_ID, #module_ID)")
For Each item In CheckedListBox1.CheckedItems
Using cmd As New SqlCommand(sb.ToString, cn)
cmd.Parameters.AddWithValue("#empl_ID", ComboBox1.SelectedValue.ToString)
cmd.Parameters.AddWithValue("#module_ID", item.ToString)
cmd.ExecuteNonQuery()
End Using
Next
End Using
End Sub

Related

DataGridView refreshing fixed position in row filter textbox in vb.net

I want when filtering rows in the textbox then the database is updated from other applications then I do a refresh I want the datagridview that I filter in the textbox in a fixed position and also when selected in the combobox as well. Maybe my code isn't perfect. So there may be the best solution.
Thanks
VIEW DATAGRIDVIEW
Public Class Form1
Dim Path As String = Application.StartupPath()
Dim cn = "provider=Microsoft.Jet.OLEDB.4.0; data source=" & Path & "; Extended Properties=dBase IV"
Private WithEvents dt As New DataTable
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.PopulateComboBox()
Me.PopulateDataGridView()
Me.clearfiltercombobox()
End Sub
Private Sub PopulateDataGridView()
Try
Dim query = "select ITM,ART,QTY FROM EXAMPLE WHERE QTY > 0 AND BRAND = #BRAND"
Using con As OleDbConnection = New OleDbConnection(cn)
Using cmd As OleDbCommand = New OleDbCommand(query, con)
cmd.Parameters.AddWithValue("#BRAND", ComboBox1.SelectedValue)
Using adapter As New OleDbDataAdapter(cmd)
Dim dt As DataTable = New DataTable()
adapter.Fill(dt)
Me.DataGridView1.DataSource = dt
End Using
End Using
End Using
Catch myerror As OleDbException
MessageBox.Show("Error: " & myerror.Message)
Finally
End Try
End Sub
Private Sub TextBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
Try
CType(DataGridView1.DataSource, DataTable).DefaultView.RowFilter = String.Format("ITM LIKE '%{0}%' OR ITM LIKE '%{0}%'", TextBox1.Text)
Catch ex As Exception
MsgBox("No match found")
End Try
End Sub
Private Sub ComboBox1_SelectionChangeCommitted(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectionChangeCommitted
Me.TextBox1.Text = ""
Me.PopulateDataGridView()
End Sub
Private Sub PopulateComboBox()
Dim query As String = "SELECT DISTINCT BRAND FROM EXAMPLE WHERE QTY > 0"
Try
Using con As OleDbConnection = New OleDbConnection(cn)
Using sda As OleDbDataAdapter = New OleDbDataAdapter(query, con)
'Fill the DataTable with records from Table.
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
'Insert the Default Item to DataTable.
Dim row As DataRow = dt.NewRow()
row(0) = ""
dt.Rows.InsertAt(row, 0)
'Assign DataTable as DataSource.
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "BRAND"
ComboBox1.ValueMember = "BRAND"
End Using
End Using
Catch myerror As OleDbException
MessageBox.Show("Error: " & myerror.Message)
Finally
End Try
End Sub
Private Sub clearfiltercombobox()
Try
ComboBox1.ResetText()
TextBox1.Text = ""
Dim query = "select ITM,ART,QTY FROM EXAMPLE WHERE QTY > 0"
Using con As OleDbConnection = New OleDbConnection(cn)
Using cmd As OleDbCommand = New OleDbCommand(query, con)
Using adapter As New OleDbDataAdapter(cmd)
Dim dt As DataTable = New DataTable()
adapter.Fill(dt)
Me.DataGridView1.DataSource = dt
End Using
End Using
End Using
Catch myerror As OleDbException
MessageBox.Show("Error: " & myerror.Message)
Finally
End Try
End Sub
Private Sub Refreshonly_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Refreshonly.Click
Me.clearfiltercombobox()
DataGridView1.Refresh()
End Sub
Private Sub clearall_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Clearall.Click
Me.clearfiltercombobox()
End Sub
End Class

refresh button for datagridview

i need help in refresh the datagridview. I create a Update button and show button but it didn't refresh. but i check in my database access it update successful
Imports System.Data
Imports System.Data.OleDb
Public Class Form2
Public con As OleDbConnection
Public da As OleDbDataAdapter
Public ds As New DataSet
Public cmd As OleDbCommand
Public dr As OleDbDataReader
Dim count As Integer = 100
Dim ID As String
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
'Establish connection
con = New OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\Users\m_j_g\Documents\Visual Studio 2010\Projects\DatabaseApplication\Department.accdb")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnShow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnShow.Click
Try
'establish connection
con = New OleDbConnection("provider = Microsoft.ACE.OLEDB.12.0; data source = C:\Users\m_j_g\OneDrive\Documents\Database1.accdb")
'execute sql query
da = New OleDbDataAdapter("Select * from table1", con)
'Fill Dataset
da.Fill(ds, "table1")
'put data from dataset to datagridview
DataGridView1.DataSource = ds.Tables(0)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnUpdate_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnUpdate.Click
con = New OleDbConnection("provider = Microsoft.ACE.OLEDB.12.0; data source = C:\Users\m_j_g\OneDrive\Documents\Database1.accdb")
Try
con.Open()
cmd = New OleDbCommand("Update table1 set SurName='" & TextBox2.Text & "', FirstName='" & TextBox3.Text & "' where EmailAddress='" & TextBox5.Text & "'", con)
'Execute UPDATE Query
cmd.ExecuteNonQuery()
MsgBox("Record Updated Successfully..." & Chr(13) & "Email Address: " & TextBox5.Text & Chr(13) & "SurName: " & TextBox2.Text & Chr(13) & "FirstName: " & TextBox3.Text)
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I am newbie in programming Thank you for your help
You need to rebind the Grid after performing the update, Follow these steps this may help you:
Define a Method for binding the giridiew, this will populate the grid with values from the DB:
Public Sub bindMyGrid()
con = New OleDbConnection("provider = Microsoft.ACE.OLEDB.12.0; data source = C:\Users\m_j_g\OneDrive\Documents\Database1.accdb")
da = New OleDbDataAdapter("Select * from table1", con)
da.Fill(ds, "table1")
DataGridView1.Rows.Clear() '<-- new line added
DataGridView1.DataSource = ds.Tables(0)
End Sub
Call the method in the click event of the show button to populate the grid:
Private Sub btnShow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnShow.Click
Try
bindMyGrid()
Catch ex As Exception
' handle error here
End Try
End Sub
Perform the update operation on update button click, and call the method again to get the latest values.
Private Sub btnUpdate_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnUpdate.Click
Try
'Perform the update operations here
' Call bindMyGrid() to rebind the grid
bindMyGrid() 'this will populate the new value to the grid.
Catch ex As Exception
'Handle error here
End Try
End Sub

“syntax error in INSERT INTO statement”

I'm a beginner in vb.net
I've got the following Error upon executing the Insert-Statement
syntax error in INSERT INTO statement
Here is my code:
Private Sub cmdadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdadd.Click
Try
Dim sql As String = " INSERT INTO [Login1] ([ID],[Username],[Password])" & _
" VALUES(?,?,?)"
Dim cmd As New OleDbCommand
With cmd
.Connection = con
.CommandText = sql
.Parameters.AddWithValue("?", txtid)
.Parameters.AddWithValue("?", txtuser)
.Parameters.AddWithValue("?", txtpass)
.ExecuteNonQuery()
End With
MsgBox("The Data Has Been Added")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Could anyone help me?
Try to use sql parameter names
Private Sub cmdadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdadd.Click
Try
Dim sql As String = " INSERT INTO [Login1] ([ID],[Username],[Password])" & _
" VALUES(#ID,#Username,#Password)"
Dim cmd As New OleDbCommand
With cmd
.Connection = con
.CommandText = sql
.Parameters.AddWithValue("#ID", txtid)
.Parameters.AddWithValue("#Username", txtuser)
.Parameters.AddWithValue("#Password", txtpass)
.Open()
.ExecuteNonQuery()
.Close()
End With
MsgBox("The Data Has Been Added")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Note that: You should properly close your connections after you use them. Therefore following code may be better.
Private Sub InsertLogin()
Dim sql As String = " INSERT INTO [Login1] ([ID],[Username],[Password])" & _
" VALUES(#ID,#Username,#Password)"
Using con As New OleDbConnection(ConnectionStringHERE)
Using cmd As New OleDbCommand
Dim cmd As New OleDbCommand
cmd.Connection = con
cmd.CommandText = sql
cmd.Parameters.AddWithValue("#ID", txtid)
cmd.Parameters.AddWithValue("#Username", txtuser)
cmd.Parameters.AddWithValue("#Password", txtpass)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
End Sub
Private Sub cmdadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdadd.Click
Try
InsertLogin()
MsgBox("The Data Has Been Added")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Here, I used cmd. syntax, it is no different then using With.
You have to name the sql parameters.
Look at the examples in the documentation: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue%28v=vs.110%29.aspx

returning select value using Visual Basic 2010 oleDB

I'm trying to read a excel cell with visual basic 2010 ( I'm really new to this) and I think I finally did it BUT I have no clue how to return the result.
It should end up in the clipboard or msgBox from there I'll find my way :D
I searched for two hours now but didnt find the solution... please help me
Thanks
Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.Click
cn.ConnectionString = "provider=microsoft.jet.oledb.4.0;data source=C:\Users\marcelf\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsApplication1\bin\Debug\DB.xls;extended properties=excel 8.0;"
cn.Open()
With cm
.Connection = cn
.CommandText = "SELECT * FROM [ccs$C1:B20] WHERE 'id' = 'German'"
.ExecuteNonQuery()
End With
cn.Close()
MsgBox(????)
End Sub
EDIT: her is the updated code. I get "Could not find installable ISAM
Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.Click
Dim con As New OleDbConnection
Try
Using con
'added HDR=No to the extended properties of the connection string
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;data source=C:\Users\marcelf\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsApplicat'ion1\bin\Debug\DB.xls;extended properties=excel 12.0;HDR=Yes"
con.Open()
Using cmd = New OleDbCommand
cmd.Connection = con
cmd.CommandText = "SELECT * FROM [ccs$C1:C20] WHERE 'id' = 'German'"
Using oRDR As OleDbDataReader = cmd.ExecuteReader
While (oRDR.Read)
MsgBox(oRDR.GetValue(0)) 'gets the first returned column
End While
End Using
con.Close()
End Using
End Using
Catch ex As Exception
Throw New Exception(ex.Message)
Finally
con.Close()
End Try
End Sub
EDIT: That's what worked for me:
Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.Click
Dim con As New OleDbConnection
Try
Using con
'added HDR=No to the extended properties of the connection string
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\marcelf\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsApplication1\bin\Debug\DB.xls;Mode=3;User ID=Admin;Password=;Extended Properties=Excel 8.0"
con.Open()
Using cmd = New OleDbCommand
cmd.Connection = con
cmd.CommandText = "SELECT Service FROM [ccs$] WHERE id='" & ComboBox1.SelectedItem & "'"
Using oRDR As OleDbDataReader = cmd.ExecuteReader
While (oRDR.Read)
MsgBox(oRDR.GetValue(0)) 'gets the first returned column
End While
End Using
con.Close()
End Using
End Using
Catch ex As Exception
Throw New Exception(ex.Message)
Finally
con.Close()
End Try
End Sub
Welcome to SO. In the future you should show us all of your code. Since you tagged OleDB and vb.net, the following implements what you are trying to accomplish. I included the Form Class so the Imports statements could be shown, but you can just copy and paste the click event code after insuring you Class includes the Imports. Note, I have not tested this code but it should work. Let me know if you need clarification or additional help.
Imports System.Data.OleDb
Public Class Form1
Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.Click
Dim con As New OleDbConnection
Try
Using con
'added HDR=No to the extended properties of the connection string
' **EDIT**
con.ConnectionString = "Provider=Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\marcelf\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsApplicat'ion1\bin\Debug\DB.xls;Mode=3;User ID=Admin;Password=;Extended Properties=Excel 8.0"
con.Open()
Using cmd = New OleDbCommand
cmd.Connection = con
cmd.CommandText = "SELECT * FROM [ccs$C1:B20] WHERE 'id' = 'German'"
Using oRDR As OleDbDataReader = cmd.ExecuteReader
While (oRDR.Read)
MsgBox(oRDR.GetValue(0)) 'gets the first returned column
End While
End Using
con.Close()
End Using
End Using
Catch ex As Exception
Throw New Exception(ex.Message)
Finally
con.Close()
End Try
End Sub
End Class

Data updation and deletion error

I have a DataGrid and many text fields to add data into the database. When i add a new data, it gets updated in the database and in the data grid.But when i delete the data, it gets deleted only from the database. It doesn't get updated in the data grid.
When i try to update the data, it updates only one record at a time.when i try for another record it gives me a error "The variable name '#date' has already been declared. Variable names must be unique within a query batch or stored procedure." I have to close and reopen the form to update a new record.
Imports System.Data.SqlClient
Public Class Form
Dim con As New SqlClient.SqlConnection("Server = DEL-PC; Database=Shj; Trusted_Connection=yes;")
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
Dim ds As DataSet
Dim da As SqlDataAdapter
Private Sub Form_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SqlDataAdapter1.Fill(DataSet11)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles newbtn.Click
If RegNoTextBox.Text <> "" Then
cmd.Connection = con
con.Open()
cmd.CommandText = "insert into WaterProofing(Date,RegNo) values ('" & DateDateTimePicker.Value & "','" & RegNoTextBox.Text & "')"
cmd.ExecuteNonQuery()
Call showdata()
con.Close()
Else
MessageBox.Show("Please enter registration number")
End If
End Sub
//updation
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles editbtn.Click
cmd.Parameters.AddWithValue("#date", DateDateTimePicker.Value)
cmd.Parameters.AddWithValue("#regno", RegNoTextBox.Text)
cmd.Connection = con
con.Open()
cmd.CommandText = "update WaterProofing set RegNo= #regno where date=#date"
cmd.ExecuteNonQuery()
Call showdata()
con.Close()
MessageBox.Show("Details Updated!")
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles deletebtn.Click
cmd.Connection = con
con.Open()
cmd.CommandText = "delete from WaterProofing where date='" & DateDateTimePicker.Value & "'"
cmd.ExecuteNonQuery()
Call showdata()
con.Close()
MessageBox.Show("Details Deleted!")
End Sub
Sub showdata()
SqlDataAdapter1.Fill(DataSet11, "WaterProofing")
With DataGridView
.Update()
End With
End Sub
End Class
Please help me in deletion and updating.
You're adding parameters before declaring CommandText at Button2_Click
Try it in this way:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles editbtn.Click
Try
Dim command As New SqlCommand
con.Open()
command.Connection = con
command.CommandText = "update WaterProofing set RegNo= #regno where date=#date"
command.Parameters.AddWithValue("#date", DateDateTimePicker.Value)
command.Parameters.AddWithValue("#regno", RegNoTextBox.Text)
command.ExecuteNonQuery()
con.Close()
Call showdata()
MessageBox.Show("Details Updated!")
Catch ex as Exception
MessageBox.Show(ex.Message)
End try
End Sub
UPDATE
Basically you have to do the same thing when you load the DataGridView for the first time in order to refresh the DataGridView with the current data from database after deleting or updating records, so your ShowData Sub might look something like this
Private Sub ShowData()
Dim Connection As SqlConnection
Connection = New SqlConnection("YourConnectionString")
Try
Connection.Open()
Dim SQL As String = "SELECT Field1, Field2, Field3 FROM Table"
Dim DS As New DataSet
Dim Adapter As New SqlDataAdapter(SQL, Connection)
Adapter.Fill(DS)
DataGridView.DataSource = DS.Tables(0)
DataGridView.Refresh()
Catch ex As Exception
MessageBox(ex.Message)
Finally
Connection.Close()
End Try
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles deletebtn.Click
Try
Dim command As New SqlCommand
con.Open()
command.Connection = con
command.CommandText = "delete from WaterProofing where date='" & DateDateTimePicker.Value & "'"
command.ExecuteNonQuery()
con.Close()
Call ShowData_Delete()
MessageBox.Show("Details Deleted!")
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
End Try
End Sub
Private Sub ShowData_Delete()
Dim Connection As SqlConnection
Try
Connection = New SqlConnection("Server = DEL-PC; Database=Shj; Trusted_Connection=yes;")
Connection.Open()
Dim SQL As String = "SELECT * from WaterProofing"
Dim DS As New DataSet
Dim Adapter As New SqlDataAdapter(SQL, Connection)
Adapter.Fill(DS)
DataGridView1.DataSource = DS.Tables(0)
DataGridView1.Refresh()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
Connection.Close()
End Try
End Sub