textbox AutoComplete not working after a search query - vb.net

Hello there I am quite new to windows form programming, and my project requires me to do a search query on my database. I would like the option for the names that can be currently searched to be displayed when typing, however, after pressing the search button the autocomplete no longer displays when I try to look for another attribute. https://i.stack.imgur.com/Wytdy.png , https://i.stack.imgur.com/Qjy5q.png
Dim con As New SQLiteConnection(ConnectionString)
Dim cmd As New SQLiteCommand(mSQL, con)
con.Open()
Dim da As New SQLiteDataAdapter(cmd)
da.Fill(ds, "customers")
dt = ds.Tables(0)
MaxRows = ds.Tables("customers").Rows.Count
con.Close()
Dim msSQL As String = "SELECT * FROM customers;"
dgvCustomerInfo.DataSource = display(msSQL, "customers")
Try
dt = New DataTable
con.Open()
With cmd
.Connection = con
.CommandText = "SELECT DISTINCT fname FROM customers"
End With
da.SelectCommand = cmd
da.Fill(dt)
Dim r As DataRow
txtSearchName.AutoCompleteCustomSource.Clear()
For Each r In dt.Rows
txtSearchName.AutoCompleteCustomSource.Add(r.Item(0).ToString)
Next
''''''''''''''''''''''''
Catch ex As Exception
MsgBox(ex.Message)
End Try
con.Close()
da.Dispose()

I believe your problems stem from the AutoCompleteMode. Suggest and SuggestAppend seem to fill in the text box as expected. Append seem to do nothing. I don't think this is working as intended.
I tested with a little database I have. It is Sql Server but should work the same for Sqlite. I used a bit of Linq magic to get the AutoCompleteCustomSource. A few other changes... Using...End Using blocks ensure that database objects are closed and disposed. You don't need a DataAdapter, just a DataTable and Command.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dt = GetDataForTextBox()
Dim strArray = dt.AsEnumerable().[Select](Function(x) x.Field(Of String)("Name")).ToArray()
TextBox5.AutoCompleteSource = AutoCompleteSource.CustomSource
Dim MySource As New AutoCompleteStringCollection()
MySource.AddRange(strArray)
TextBox5.AutoCompleteCustomSource = MySource
TextBox5.AutoCompleteMode = AutoCompleteMode.SuggestAppend
End Sub
Private Function GetDataForTextBox() As DataTable
Dim dt As New DataTable
Using cn As New SqlConnection(My.Settings.CoffeeConnection),
cmd As New SqlCommand("Select Distinct Name From Coffees", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt = GetSearchResults(TextBox5.Text)
DataGridView1.DataSource = dt
End Sub
Private Function GetSearchResults(name As String) As DataTable
Dim dt As New DataTable
Using cn As New SqlConnection(My.Settings.CoffeeConnection),
cmd As New SqlCommand("Select * From Coffees Where Name = #Name", cn)
cmd.Parameters.Add("#Name", SqlDbType.VarChar, 100).Value = name
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function

Related

Combobox population does not appear in DataGridView in vb.net

Combobox population does not appear in DataGridView because of the function of DataTable.
below link the previous code running normally with the combobox population.
please recommend the best solution.
I have also coded in my post so it doesn't miss communication
Thanks
link previous post
Private _dt As DataTable
'update code PopulateComboBox in form load
Public Sub New()
If Me.IsInDesignMode() Then
Return
End If
InitializeComponent()
Me.PopulateComboBox()
fillDataGridView1()
End Sub
Private Function GetAndFillDataTable() As DataTable
Dim dt As New DataTable()
Dim query As String = "SELECT NOD,ITM,CIA,DPR,QTY FROM RSD WHERE QTY > 0 AND PNM=#PNM"
Using con As OleDbConnection = New OleDbConnection(GetConnectionString)
Using cmd As OleDbCommand = New OleDbCommand(query, con)
cmd.Parameters.AddWithValue("#PNM", ComboBox1.SelectedValue)
Using da As New OleDbDataAdapter(cmd)
da.Fill(dt)
da.Dispose()
Dim totalColumn As New DataColumn()
totalColumn.DataType = System.Type.GetType("System.Double")
totalColumn.ColumnName = "Total"
totalColumn.Expression = "[CIA]*[QTY]*(1-[DPR]/100)"
dt.Columns.Add(totalColumn)
Return dt
End Using
End Using
End Using
End Function
Private Sub FillDataGridView1()
If (_dt Is Nothing) Then
_dt = GetAndFillDataTable()
End If
grid.DataSource = _dt
grid.Refresh()
End Sub
Private Sub PopulateComboBox()
Dim dt As New DataTable()
Dim query As String = "SELECT DISTINCT PNM FROM RSD UNION SELECT DISTINCT PNM FROM RSG ORDER BY PNM"
Try
dt = New DataTable
Using con As OleDbConnection = New OleDbConnection(GetConnectionString)
Using sda As OleDbDataAdapter = New OleDbDataAdapter(query, con)
sda.Fill(dt)
Dim row As DataRow = dt.NewRow()
row(0) = ""
dt.Rows.InsertAt(row, 0)
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "PNM"
ComboBox1.ValueMember = "PNM"
End Using
End Using
Catch myerror As OleDbException
MessageBox.Show("Error: " & myerror.Message)
Finally
End Try
'update code combobox selectionchangecommited for fillDataGridView1
Private Sub ComboBox1_SelectionChangeCommitted(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectionChangeCommitted
fillDataGridView1()
End Sub
You are setting your datasource = _dt in PopulateComboBox however the data table you built in your function is called dt.

How to use DataGridView checkbox in Combobox's Select Change event?

I want to create a mobile phone project in VB.net 2019. Where the model of the mobile phone in the Combobox came from the database. I have attached a datagridview where the IMEI number of the mobile phone is displayed. An attached checkbox in Datagridview. The problem is that when I go to change the model number of the mobile phone in the change event of Combobox, a new checkbox is added to every change in Datagridview.
I created a searchbox to easily find IEMI numbers in a textbox. When I search the IEMI number in the search box in the datagridview and check in the datagridview checkbox and search for the next number, the previous one is unchecked
I am praying for the help of the experienced.
Sub display_data()
con.Open()
Dim cmd As New SqlCommand("select Product_Name, IMEI_No,qty from tbl_Stock where Company_Name=#d1 and Product_Name =#d2", con)
cmd.Parameters.Add("#d1", SqlDbType.NVarChar).Value = cmb_cmp.Text
cmd.Parameters.Add("#d2", SqlDbType.NVarChar).Value = cmb_pro.Text
Dim da As New SqlDataAdapter(cmd)
Dim dt As New DataTable
dt.Clear()
da.Fill(dt)
DataGridView1.DataSource = dt
con.Close()
Dim chakbox As New DataGridViewCheckBoxColumn
chakbox.Width = 60
chakbox.Name = "checkbox"
DataGridView1.Columns.Insert(0, chakbox)
End Sub
Private Sub ComboBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmb_pro.SelectedIndexChanged
con.Open()
Dim strsql As New SqlCommand("Select * from tbl_pro where Product_name=#d1", con)
strsql.Parameters.Add("#d1", SqlDbType.NVarChar).Value = cmb_pro.Text
Dim myreader As SqlClient.SqlDataReader = strsql.ExecuteReader
While myreader.Read
txt_sal_rt.Text = myreader.GetDecimal("sale_rate")
txt_pro_cod.Text = myreader.GetString("product_code")
txt_pur_rt.Text = myreader.GetDecimal("Purchase_rate")
End While
con.Close()
display_data()
End Sub
Private Sub txt_serch_KeyUp(sender As Object, e As KeyEventArgs) Handles txt_serch.KeyUp
DataGridView1.DataSource = searech()
End Sub
Private Function searech() As DataTable
Dim cmd As New SqlCommand("select Product_Name, IME_No,qty from tbl_Stock where Company_Name=#d1 and IME_NO Like '%' +#d2 + '%'", con)
cmd.Parameters.Add("#d1", SqlDbType.NVarChar).Value = cmb_cmp.Text
cmd.Parameters.Add("#d2", SqlDbType.VarChar).Value = txt_serch.Text
Dim da As New SqlDataAdapter(cmd)
Dim dt As New DataTable
da.Fill(dt)
Return dt
End Function
Just put a bool in your query, throw that "add a checkbox to the grid" code away
Sub display_data()
con.Open()
Dim cmd As New SqlCommand("select CAST(0 as BIT) as checkbox, Product_Name, IMEI_No,qty from tbl_Stock where Company_Name=#d1 and Product_Name =#d2", con)
cmd.Parameters.Add("#d1", SqlDbType.NVarChar).Value = cmb_cmp.Text
cmd.Parameters.Add("#d2", SqlDbType.NVarChar).Value = cmb_pro.Text
Dim da As New SqlDataAdapter(cmd)
Dim dt As New DataTable
dt.Clear()
da.Fill(dt)
DataGridView1.DataSource = dt
con.Close()
End Sub

Multiple DataGridView on TabPages. vb.net

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
abc()
Refresh()
Dim con As String = "Data Source = HCA-ISD03\SQLEXPRESS; Initial Catalog = QMS_HCA; User ID=qs; Password=ZAQ!2wsx; MultipleActiveResultSets=True"
Dim conn As New SqlConnection(con)
Dim Query As String = Nothing
Dim Query2 As String = Nothing
Dim Query3 As String = Nothing
Dim adapter As New SqlDataAdapter
Dim adapter1 As New SqlDataAdapter
Dim ds As New DataSet()
Dim table As New DataTable()
Dim cmd1 As New SqlCommand
Query = "Select sMessage, iAlert FROM MAS_Alert"
Query2 = "SELECT REF_AlertPlate.sPlateNo, MAS_Alert.sMessage, REF_AlertPlate.iAlert, REF_AlertPlate.dStart, REF_AlertPlate.dEnd, REF_AlertPlate.sFrameNo FROM REF_AlertPlate INNER JOIN MAS_Alert ON MAS_Alert.iAlert=REF_AlertPlate.iAlert"
Query3 = "SELECT iAlert, sMessage, dCreated, iCreatedBy FROM MAS_Alert"
Try
conn.Open()
adapter.SelectCommand = cmd
adapter.SelectCommand = New SqlCommand(Query, conn)
adapter.SelectCommand = New SqlCommand(Query2, conn)
adapter.SelectCommand = New SqlCommand(Query3, conn)
adapter.Fill(ds)
adapter.Dispose()
cmd.Dispose()
ComboBox1.Items.Clear()
DataGridView2.DataSource = ds.Tables(0)
DataGridView1.DataSource = ds.Tables(1)
ComboBox1.DataSource = Nothing
ComboBox1.Refresh()
ComboBox1.DataSource = ds.Tables(0)
ComboBox1.ValueMember = "iAlert"
ComboBox1.DisplayMember = "sMessage"
Catch ex As Exception
End Try
conn.Close()
End Sub
How can I load the datagridView1? The only DataGridView that loads is the DataGridView2. Sorry if I'm wrong, I set the three queries in the formload. What should I do first?? The only query that loads is the Query and Query2Thank you in advance mates. Hope that you can help me.
I've created another sub for the DataGridView1 then call it in FormLoad
Sub Query3()
Dim con As String = "Data Source = HCA-ISD03\SQLEXPRESS; Initial Catalog = QMS_HCA; User ID=qs; Password=ZAQ!2wsx; MultipleActiveResultSets=True"
Dim conn As New SqlConnection(con)
Dim Query3 As String = Nothing
Dim adapter As New SqlDataAdapter
Dim adapter1 As New SqlDataAdapter
Dim ds As New DataSet()
Dim table As New DataTable()
Dim cmd1 As New SqlCommand
Query3 = "SELECT iAlert, sMessage, dCreated, iCreatedBy FROM MAS_Alert"
Try
conn.Open()
adapter.SelectCommand = cmd
adapter.SelectCommand = New SqlCommand(Query3, conn)
adapter.Fill(ds)
adapter.Dispose()
cmd.Dispose()
DataGridView1.DataSource = ds.Tables(0)
Catch ex As Exception
End Try
conn.Close()
End Sub
Problem Solved. Sorry if I made a mistake.

show database values in listbox when you open a form

I'm just new to vb.net.. Anyway, Is there a way when I open my form the items in my database will show up automatically?
Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
list()
End Sub
Sub list()
con.Open()
cmd = New SqlCommand("SELECT * FROM Tbl", con)
rdr = cmd.ExecuteReader
ListView1.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("Brand")
itm = New ListViewItem(arr)
ListView1.Items.Add(itm)
Loop
End If
con.Close()
End Sub
You can use below code
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("SELECT * FROM Tbl")
cmd.Connection = con
Using sda As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
End Using
End Using
End Using
Dim list As List(Of DataRow) = dt.AsEnumerable().ToList()
this code can convert direct data table to list.

add items from access to combobox vb.net

I want to fill a combobox with items from ms access database.
here's my code..
conn = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ainunandile\Desktop\ElectionDB.mdb;Persist Security Info=False;")
conn.Open()
sqlQry = "SELECT * FROM Candidates where Position='President'"
cmd = New OleDbCommand(sqlQry, conn)
rdr = cmd.ExecuteReader
While rdr.Read()
ComboBox1.Items.Add(rdr("CandidateName").ToString())
End While
however the combobox won't fill up, but if i remove the "where Position ='President'" the code works, can someone help me i've been stuck here for hours.
you can try this i hope this work.
Dim cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ainunandile\Desktop\ElectionDB.mdb;Persist Security Info=False;")
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cn.Open()
Dim cm As New OleDbCommand("select * from Candidates where Position='President'", cn)
Dim dr As OleDbDataReader = cm.ExecuteReader
While dr.Read
ComboBox1.Items.Add(dr(1).ToString)
End While
dr.Close()
cn.Close()
End Sub