show database values in listbox when you open a form - vb.net

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.

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.

textbox AutoComplete not working after a search query

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

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.

Cascading ComboBoxes

I am trying to create a cascading ComboBox that is populated from a SQL data set.
My problem is I am not getting any errors when compiling the code. but the two ComboBoxes are not populating as intended with data. Can you help me find where I am making the mistake?
Private Sub FillSalesPerson()
Dim strConnString As String
strConnString = ConfigurationManager.ConnectionStrings("con").ConnectionString
Dim DS As New SqlConnection(strConnString)
Dim cmd As New SqlCommand()
cmd.Connection = DS
cmd.CommandType = CommandType.Text
cmd.CommandText = "select distinct Name,Salesperson_Code from dbo.View_Customers_With_Sales_People"
Dim objeDS As DataSet = New DataSet()
Dim dAdapter As New SqlDataAdapter
dAdapter.SelectCommand = cmd
DS.Open()
dAdapter.Fill(objeDS)
DS.Close()
ComboBox1.ValueMember = "Salesperson_Code"
ComboBox1.DisplayMember = "Name"
ComboBox1.DataSource = objeDS.Tables(0)
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
If ComboBox1.SelectedValue.ToString() <> " " Then
Dim Salesperson_Code As Integer = Convert.ToInt32(ComboBox1.SelectedValue.ToString())
FillStates(Salesperson_Code)
'ComboBox2.SelectedIndex = 0'
End If
End Sub
Private Sub FillStates(Salesperson_Code As Integer)
Dim strConnString As String = ConfigurationManager.ConnectionStrings("con").ConnectionString
Dim DS As New SqlConnection(strConnString)
Dim cmd As New SqlCommand()
cmd.Connection = DS
cmd.CommandType = CommandType.Text
cmd.CommandText = "Select [No_],[Company Name] from [dbo].[View_Customers_With_Sales_People] where (Salesperson_Code= #Salesperson_Code)"
cmd.Parameters.AddWithValue("#Salesperson_Code", Salesperson_Code)
Dim objDs As New DataSet()
Dim adapter As New SqlDataAdapter()
adapter.SelectCommand = cmd
DS.Open()
adapter.Fill(objDs)
DS.Close()
If objDs.Tables(0).Rows.Count > 0 Then
ComboBox2.ValueMember = "[No_]"
ComboBox2.DisplayMember = "[Company Name]"
ComboBox2.DataSource = objDs.Tables(0)
End If
End Sub
Try changing ComboBox1.DataSource = objeDS.Tables(0) for ComboBox1.RowSource = objeDS.Tables(0)

add autocomplete to textbox in vb.net

I've created a code for autocompletion, but dont know why it doesn't work.
Private Sub btnrefresh_Click(sender As Object, e As EventArgs) Handles btnrefresh.Click
txtledgersearch.AutoCompleteMode = AutoCompleteMode.Suggest
txtledgersearch.AutoCompleteSource = AutoCompleteSource.CustomSource
Dim DataCollection As New AutoCompleteStringCollection()
getData(DataCollection)
txtledgersearch.AutoCompleteCustomSource = DataCollection
End Sub
Private Sub getData(ByVal dataCollection As AutoCompleteStringCollection)
On Error Resume Next
Dim adapter As New OleDbDataAdapter
con = New OleDbConnection(connectionString)
con.Open()
Dim dt As New DataTable
Dim ds As New DataSet
sqlstr = "SELECT LedgerTab.lname FROM LedgerTab;"
ds.Tables.Add(dt)
adapter.SelectCommand = New OleDbCommand(sqlstr, con)
For Each row As DataRow In ds.Tables(0).Rows
dataCollection.Add(row(0).ToString())
Next
End Sub
I'm not getting why my code is not working.
Check whether data is filled to dataCollection from DB.
try moving this scode snipet to load event
txtledgersearch.AutoCompleteMode = AutoCompleteMode.Suggest
txtledgersearch.AutoCompleteSource = AutoCompleteSource.CustomSource
Dim DataCollection As New AutoCompleteStringCollection()
getData(DataCollection)
txtledgersearch.AutoCompleteCustomSource = DataCollection