how to make a ComboBox predictive (AutoSelective) in Vb.net [duplicate] - vb.net

This question already has answers here:
VB.net ComboBox auto drop down on input
(2 answers)
Closed 6 years ago.
I am populating the items of ComboBox from Database. Now I want to give Combobox a functionality such that, as soon as user type few letters or a word, it automatically selects and displays the item containing those alphabets or words. Presently I have written following lines of code
Private Sub From1_Load(By val connection = New OledbConnection("Data Source")
con.Open()
cmd = New OledbCommand("SQL",con)
DataReader = cmd.ExecuteReader
While DataReader.Read
ComboBox1.items.Add(DataReader(0))
End While
Con.Close()

Set the following properties of the ComboBox before filling
ComboBox1.AutoCompleteSource = AutoCompleteSource.ListItems
ComboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend

Imports System.Data.OleDb
Public Class Form1
Dim conn As New OleDbConnection
Dim reader1 As OleDbDataReader
Dim strSQL As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.connect()
Me.fillcombo()
End Sub
Sub connect()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Nick\Desktop\aswer\aswer\databee.accdb"
conn.Open()
End Sub
Sub fillcombo()
strSQL = "select * from Table1"
Dim cmd As New OleDb.OleDbCommand
cmd.CommandText = strSQL
cmd.Connection = conn
reader1 = cmd.ExecuteReader
While (reader1.Read())
ComboBox1.Items.Add(reader1("ID Number"))
End While
cmd.Dispose()
reader1.Close()
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
strSQL = "select * from Table1 where id='" & ComboBox1.Text & "'"
Dim comnd As New OleDb.OleDbCommand
comnd.CommandText = strSQL
comnd.Connection = conn
reader1 = comnd.ExecuteReader
If (reader1.Read() = True) Then
TextBox1.Text = (reader1("Name"))
End If
comnd.Dispose()
reader1.Close()
End Sub
End Class

Related

Update statement in sql doesnt work , microsoft access with vb.net

I currently doing the changepassword function in my vb.net project, user can click change password to change their password
But my code doesnt update correctly , it will show "updated" but when i go to my database access table the data still remain the same
Imports System.Data.OleDb
Imports System.Data.SqlClient
Imports System.IO
Public Class frmUserDetail
Dim ds As New DataSet
Dim dt As New DataTable
Dim cmd As SqlCommand
Dim con As SqlConnection
Dim da As New OleDbDataAdapter
Dim conn As New OleDbConnection
Private Sub FrmUserDetail_Load(sender As Object, e As EventArgs) Handles MyBase.Load
conn.ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\phoneOnline.accdb;Persist Security Info=false;")
loadUserDetail()
txtUserName.Enabled = False ' set it to false so user cannot do shit with it
End Sub
Public Sub loadUserDetail()
conn.ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\phoneOnline.accdb;Persist Security Info=false;")
Dim cmd As OleDbCommand
Dim userName As String = frmMain.lblUserLogin.Text
'specify name of the user
Dim search As String = "SELECT * from tblUser WHERE UserName= '" + userName + "'"
cmd = New OleDbCommand(search)
cmd.Connection = conn
Dim dtt As New DataTable()
Dim daa As New OleDbDataAdapter(cmd)
daa.Fill(dtt)
If dtt.Rows.Count() > 0 Then
txtUserName.Text = dtt.Rows(0)(0).ToString 'show the userName
txtUserPassword.Text = dtt.Rows(0)(1).ToString 'show the password of the user
txtEmail.Text = (dtt.Rows(0)(2).ToString) 'show user email
Else
MsgBox("You are currently login as a guest")
End If
End Sub
Private Sub changePassword()
If cbChangePassword.Checked Then
txtChangePassword.Enabled = True
Else
txtChangePassword.Enabled = Not (True)
End If
End Sub
Private Sub CbChangePassword_CheckedChanged(sender As Object, e As EventArgs) Handles cbChangePassword.CheckedChanged
changePassword()
End Sub
Private Sub BtnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
conn.Open()
Dim cmd As OleDbCommand
Dim sql As String = "UPDATE tblUser SET UserPassword=#userpass,Email=#email WHERE UserName=#userName;"
cmd = New OleDbCommand(sql.ToString, conn)
cmd.Parameters.AddWithValue("#username", txtUserName.Text)
cmd.Parameters.AddWithValue("#userpass", txtChangePassword.Text)
cmd.Parameters.AddWithValue("#email", txtEmail.Text) 'pass the time variable from the form 1 to the parameter
cmd.ExecuteNonQuery()
MsgBox("updated")
conn.Close()
End Sub
Private Sub BtnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Hide()
frmMain.Show()
End Sub
End Class
I Expect my database will get updated when i updated it

How do I put the items I picked in listview to my database?

See pic
Just new to vb.net. Anyway, I don't know how I will put the value of product and price I picked in the database since it's in the list view. I tried
Dim txtValue as String
txtValue = ListView1.FocusedItem.SubItems(0).text. To get the values of the columns.
In the picture I provided, If I the put the customername and I pick her order in the listview1 it will save in my database. And it will show it my listview2. Just disregard the address.
UPDATE I think this code works but there's still error message showing up.Error message see pic
Imports System.Data.SqlClient
Imports System.IO
Public Class Form1
Dim con As SqlConnection = New SqlConnection("server=.\SQL;database=try;Trusted_Connection=TRUE")
Dim cmd As SqlCommand
Dim cmd2 As SqlCommand
Dim rdr As SqlDataReader
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
con.Open()
con.Close()
list()
list2()
End Sub
Sub list()
con.Open()
cmd = New SqlCommand("SELECT * FROM ProductTable", con)
rdr = cmd.ExecuteReader
ListView1.Items.Clear()
If rdr.HasRows Then
Do While rdr.Read()
Dim arr As String() = New String(2) {}
Dim itm As ListViewItem
arr(0) = rdr("productID")
arr(1) = rdr("product")
arr(2) = rdr("price")
itm = New ListViewItem(arr)
ListView1.Items.Add(itm)
Loop
End If
con.Close()
End Sub
Private Sub btnsave_Click(sender As Object, e As EventArgs) Handles btnsave.Click
modifyrecord("Insert into ProductOrder([name],[product],[price]) values ('" & txtname.Text & "','" & ListView1.SelectedItems(0).SubItems(1).Text & "'," & ListView1.SelectedItems(0).SubItems(2).Text & "")
End Sub
Private Sub listView1_MouseClick_1(ByVal sender As Object, ByVal e As MouseEventArgs)
End Sub
Sub list2()
con.Open()
cmd2 = New SqlCommand("SELECT * FROM ProductOrder", con)
rdr = cmd2.ExecuteReader
ListView2.Items.Clear()
If rdr.HasRows Then
Do While rdr.Read()
Dim arr As String() = New String(3) {}
Dim itm As ListViewItem
arr(0) = rdr("id")
arr(1) = rdr("name")
arr(2) = rdr("product")
arr(3) = rdr("price")
itm = New ListViewItem(arr)
ListView2.Items.Add(itm)
Loop
End If
con.Close()
End Sub
Sub modifyrecord(ByVal sql)
If txtname.Text = "" Or ListView1.SelectedItems(0).SubItems(1).Text = "" Or IsNumeric(ListView1.SelectedItems(0).SubItems(2).Text) = False Then
Else
con.Open()
cmd = New SqlCommand(sql, con)
cmd.ExecuteNonQuery()
con.Close()
list()
End If
End Sub
End Class
Try this
txtValue = ListView1.SelectedItems(0).SubItems(1).Text
txtValue1 = ListView1.SelectedItems(0).SubItems(2).Text
To get the Product and price from the list view
I assume you have the MultiSelect set to false.

how to insert checked items from checkedlistbox to SQL database?

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.

Displaying Data from SQL in TextBox by clicking ComboBox item in Visual Basic 2012

I have three columns in SQL, which I want the data displayed in three textboxes by clicking an item in ComboBox.
The issue is not really displaying. I can save the data fine and display. However, one of the text fields will only show one cell and not update when a different item is selected. Hope this is making sense.
Here is the code I have for saving:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myconnect As New SqlClient.SqlConnection
myconnect.ConnectionString = "Data Source=.\INFLOWSQL;Initial Catalog=RioDiary;Integrated Security=True"
Dim mycommand As SqlClient.SqlCommand = New SqlClient.SqlCommand()
mycommand.Connection = myconnect
mycommand.CommandText = "INSERT INTO MyDiary (Title, DiaryContent, DiaryDate) VALUES (#Title, #DiaryContent, #DiaryDate)"
myconnect.Open()
Try
mycommand.Parameters.Add("#Title", SqlDbType.VarChar).Value = TextBox1.Text
mycommand.Parameters.Add("#DiaryContent", SqlDbType.VarChar).Value = TextBox2.Text
mycommand.Parameters.Add("#DiaryDate", SqlDbType.VarChar).Value = TextBox3.Text
mycommand.ExecuteNonQuery()
MsgBox("Success")
Catch ex As System.Data.SqlClient.SqlException
And here is the code for displaying in form1:
Imports System.Data.SqlClient
Public Class Form1
Dim con As New SqlConnection
Dim ds As New DataSet
Dim da As New SqlDataAdapter
Dim sql As String
Dim inc As Integer
Dim MaxRows As Integer
Dim max As String
Dim dt As New DataTable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'RioDiaryDataSet5.MyDiary' table. You can move, or remove it, as needed.
Me.MyDiaryTableAdapter.Fill(Me.RioDiaryDataSet5.MyDiary)
Dim con As New SqlConnection(" Data Source=.\INFLOWSQL;Initial Catalog=RioDiary;Integrated Security=True")
Dim cmd As New SqlCommand("Select Title,DiaryContent,DiaryDate FROM MyDiary ")
Dim da As New SqlDataAdapter
da.SelectCommand = cmd
cmd.Connection = con
da.Fill(ds, "MyDiary")
con.Open()
ComboBox1.DataSource = ds.Tables(0)
ComboBox1.DisplayMember = "Title'"
ComboBox1.ValueMember = "DiaryContent"
End Sub
Private Sub NewEntryToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NewEntryToolStripMenuItem.Click
AddEntry.Show()
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
If (Not Me.ComboBox1.SelectedValue Is Nothing) Then
Me.TextBox2.Text = ComboBox1.Text
Me.TextBox3.Text = ComboBox1.SelectedValue.ToString
End If
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
If dt.Rows.Count > 0 Then
TextBox1.Text = dt.Rows(0)("DiaryDate").ToString() 'Where ColumnName is the Field from the DB that you want to display
End If
End Sub
End Class
As you can see from the code, I want to display Title and DiaryContent in two separate textboxes by clicking on Title in the Combobox. This works fine.
The issue I have is DiaryDate only shows the first entry and does not update when selecting the Item from ComboBox.
Can anyone help?
You can try to play with ComboBox's SelectedItem property. Since ComboBox's DataSource is DataTable here, SelectedItem of ComboBox represent a row in DataTable. Given DataRow in hand, you can display value of any column of DataRow in TextBoxes :
........
If (Not Me.ComboBox1.SelectedItem Is Nothing) Then
Dim SelectedItem = TryCast(comboBox1.SelectedItem, DataRowView)
Me.TextBox1.Text = SelectedItem.Row("Title").ToString()
Me.TextBox2.Text = SelectedItem.Row("DiaryContent").ToString()
Me.TextBox3.Text = SelectedItem.Row("DiaryDate").ToString()
End If
........
Public Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim cn As New SqlClient.SqlConnection("Data Source=thee-pc;Initial Catalog=jobportal;Integrated Security=True")
Dim cmd As New SqlClient.SqlCommand
Dim tbl As New DataTable
Dim da As New SqlClient.SqlDataAdapter
Dim reader As SqlClient.SqlDataReader
Try
cn.Open()
Dim sql As String
sql = "select * from Register"
cmd = New SqlClient.SqlCommand(sql, cn)
reader = cmd.ExecuteReader
While reader.Read
Dim id = reader.Item("cid")
ComboBox1.Items.Add(id)
End While
cn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim cn As New SqlClient.SqlConnection("Data Source=thee-pc;Initial Catalog=jobportal;Integrated Security=True")
Dim cmd As New SqlClient.SqlCommand
Dim tbl As New DataTable
Dim da As New SqlClient.SqlDataAdapter
Dim reader As SqlClient.SqlDataReader
Try
cn.Open()
Dim sql As String
sql = "select * from register where cid ='" + ComboBox1.Text + "'"
cmd = New SqlClient.SqlCommand(sql, cn)
reader = cmd.ExecuteReader
While reader.Read
TextBox1.Text = reader.Item("cname")
TextBox2.Text = reader.Item("dob")
End While
cn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

Listbox Database

Okay, so for a project I'm not allowed to use Datagridview and instead I'll have to use a Listbox to display data from a database when it is searched for. I'll link my code below, could anyone please tell me how I can change this code to suit a listbox. I'm a noob to programming so if I've made any obvious mistakes please forgive me
Imports System.Data
Imports System.Data.OleDb
Public Class frmUserList
Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
Me.Close()
End Sub
Private Sub Load_Record()
Dim conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim da As New OleDbDataAdapter
Dim dt As New DataTable
Dim sSQL As String = String.Empty
'try catch block is used to catch the error
Try
'get connection string declared in the Module1.vb and assing it to conn variable
conn = New OleDbConnection(Get_Constring)
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
sSQL = "SELECT user_id, last_name + ', ' + first_name + ' ' + mid_name as name FROM users where last_name + ', ' + first_name + ' ' + mid_name like '%" & Me.txtSearch.Text & "%' or [first_name] = '" & Me.txtSearch.Text & "'"
cmd.CommandText = sSQL
da.SelectCommand = cmd
da.Fill(dt)
Me.dtgResult.DataSource = dt
If dt.Rows.Count = 0 Then
MsgBox("No record found!")
End If
Catch ex As Exception
MsgBox(ErrorToString)
Finally
conn.Close()
End Try
End Sub
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
Load_Record()
End Sub
Private Sub dtgResult_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtgResult.DoubleClick
If Me.dtgResult.SelectedRows.Count > 0 Then
Dim frm As New frmMarkSeat
frm.txtFname.Tag = Me.dtgResult.Item(0, Me.dtgResult.CurrentRow.Index).Value
frm.ShowDialog()
frm = Nothing
End If
End Sub
End Class
Give this a try using SQLDataReader: (untested code, just wrote out of hand).
'start here
conn.Connection.Open()
Dim sqlDR As SqlDataReader
Dim colValue As String
sqlDR = conn.ExecuteReader
While sqlDR.Read
colValue = (sqlDR.GetValue(0)).ToString
ItemlistBox.Items.Add(colValue)
ItemlistBox.Sorted = True
End While
conn.Connection.Close()
Or you can keep using your current objects, with additional object DataSet and populate the listbox.
Dim dtset As New DataSet
Dim da As New OleDbDataAdapter
da.Fill(dtset)
ItemListBox.DataSource = dtset
ItemListBox.DisplayMember = "ColName"