add autocomplete to textbox in vb.net - 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

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.

Get Image from SQL using Listbox to picturebox VB

i'm trying to get the image from SQL to picturebox using Listbox in in VB.
here is my sql sample table.
and here is my VB Design form, so what I'm trying to do is when I load the form, if an item in the listbox is selected, i want it to get the image(Binary Data) from sql to picturebox in vb net.
and the code I'm working with it give me this error:
VB full code:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
connect()
Dim co As New SqlConnection("Data Source=WXCQSDQSD\SQLEXPRESS;Initial Catalog=food;Integrated Security = True")
co.Open()
Dim com As New SqlCommand("SELECT Image from Items where ItemName = '" & ListBox1.SelectedIndex & "'", co)
Dim img As Byte() = DirectCast(com.ExecuteScalar(), Byte())
Dim ms As MemoryStream = New MemoryStream(img)
Dim dt = GetDataFromSql()
Dim BndSrc As New BindingSource()
BndSrc.DataSource = dt
ListBox1.DisplayMember = "ItemName"
ListBox1.DataSource = BndSrc
TextBox1.DataBindings.Add("Text", BndSrc, "ItemID")
TextBox2.DataBindings.Add("Text", BndSrc, "ItemName")
TextBox3.DataBindings.Add("Text", BndSrc, "Details")
PictureBox1.Image = Image.FromStream(ms)
End Sub
Private Function GetDataFromSql() As DataTable
Dim dt As New DataTable
Using connection As New SqlConnection("Data Source=WXCQSDQSD\SQLEXPRESS;Initial Catalog=food;Integrated Security = True"),
cmd As New SqlCommand("select * FROM Items", connection)
connection.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
Remove the picture retrieval from the Form.Load. We have selected all the data in the GetDataFromSql function. The magic happens in the ListBox1.SelectedIndexChanged method.
The SelectedIndexChanged will occur as a result of the code in the Form.Load and every time the selection changes. When we bind the the list box to to binding source the entire row is added as a DataRowView. We can use this to get the data in the Image column. First check if the field is null. Next cast to a byte array. Take the byte array and pass it to the constructor of a MemoryStream. Streams need to be disposed so it is in a Using block. Finally the stream can be assigned to the Image property of the PictureBox.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dt = GetDataFromSql()
Dim BndSrc As New BindingSource()
BndSrc.DataSource = dt
ListBox1.DisplayMember = "ItemName"
ListBox1.DataSource = BndSrc
TextBox1.DataBindings.Add("Text", BndSrc, "ItemID")
TextBox2.DataBindings.Add("Text", BndSrc, "ItemName")
TextBox3.DataBindings.Add("Text", BndSrc, "Details")
End Sub
Private Function GetDataFromSql() As DataTable
Dim dt As New DataTable
Using connection As New SqlConnection("Data Source=WXCQSDQSD\SQLEXPRESS;Initial Catalog=food;Integrated Security = True"),
cmd As New SqlCommand("select * FROM Items", connection)
connection.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
Dim row = DirectCast(ListBox1.SelectedItem, DataRowView)
If row("Image") IsNot Nothing Then
Dim b() As Byte = DirectCast(row("Image"), Byte()) '< ------ Cast the field to a Byte array.
Using ms As New System.IO.MemoryStream(b)
PictureBox1.Image = System.Drawing.Image.FromStream(ms)
End Using
Else
PictureBox1.Image = Nothing
End If
End Sub
EDIT
I switched the code over to a database I have available for testing. Even though it is not your database, I am sure you will be able to follow the code.
Here is the schema of my database.
The main difference is I moved the DataTable to a class level variable so it can be seen from all methods. I changed the GetDataFromSql to a Sub. It adds the data to the class level DataTable (Bounddt). The AddItem method first gets the Byte() from a file. The row is added to the DataTable with an Object array with elements that match the DataTable.
Private Bounddt As New DataTable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
GetDataFromSql()
Dim BndSrc As New BindingSource()
BndSrc.DataSource = Bounddt
ListBox1.DisplayMember = "CustomerID"
ListBox1.DataSource = BndSrc
TextBox1.DataBindings.Add("Text", BndSrc, "CustomerID")
TextBox2.DataBindings.Add("Text", BndSrc, "CustomerName")
End Sub
Private Sub GetDataFromSql()
Using connection As New SqlConnection("Data Source=****;Initial Catalog='Small Database';Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"),
cmd As New SqlCommand("select * FROM Sales.Customer", connection)
connection.Open()
Using reader = cmd.ExecuteReader
Bounddt.Load(reader)
End Using
End Using
'Return dt
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
Dim row = DirectCast(ListBox1.SelectedItem, DataRowView)
If row("Picture") IsNot Nothing Then
Dim b() As Byte = DirectCast(row("Picture"), Byte()) '< ------ Cast the field to a Byte array.
Using ms As New System.IO.MemoryStream(b)
PictureBox1.Image = System.Drawing.Image.FromStream(ms)
End Using
Else
PictureBox1.Image = Nothing
End If
End Sub
Private Sub AddItem()
Dim picture = GetByteArr("C:\Users\maryo\OneDrive\Documents\Graphics\Animals\squirrel.png")
Bounddt.Rows.Add({5, "George", 74, 62, "George", picture})
End Sub
Private Function GetByteArr(path As String) As Byte()
Dim img = Image.FromFile(path)
Dim arr As Byte()
Dim imgFor As Imaging.ImageFormat
Dim extension = path.Substring(path.LastIndexOf(".") + 1)
'There is a longer list of formats available in ImageFormat
Select Case extension
Case "png"
imgFor = Imaging.ImageFormat.Png
Case "jpg", "jpeg"
imgFor = Imaging.ImageFormat.Jpeg
Case "bmp"
imgFor = Imaging.ImageFormat.Bmp
Case Else
MessageBox.Show("Not a valid image format")
Return Nothing
End Select
Using ms As New MemoryStream
img.Save(ms, imgFor)
arr = ms.ToArray
End Using
Return arr
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
AddItem()
End Sub
Imports System.Data.SqlClient
Imports System.IO
Public Class Form1
Dim con As SqlConnection
Dim cmd As SqlCommand
Dim rdr As SqlDataReader
Dim da As SqlDataAdapter
Private Const cs As String = "ConnectionString"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
con = New SqlConnection(cs)
con.Open()
cmd = New SqlCommand("select * from [dbo].[Item_Details]", con)
rdr = cmd.ExecuteReader()
While rdr.Read
ListBox1.Items.Add(rdr(1))
End While
con.Close()
End Sub
Private Sub ListBox1_MouseClick(sender As Object, e As MouseEventArgs) Handles ListBox1.MouseClick
Try
con = New SqlConnection(cs)
con.Open()
da = New SqlDataAdapter("Select * from Item_Details where itemname='" & ListBox1.SelectedItem.ToString() & "'", con)
Dim dt As New DataTable
da.Fill(dt)
For Each row As DataRow In dt.Rows
TextBox1.Text = row(0).ToString()
TextBox2.Text = row(1).ToString()
TextBox3.Text = row(2).ToString()
Dim data As Byte() = row(3)
Dim ms As New MemoryStream(data)
PictureBox1.Image = Image.FromStream(ms)
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class

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.

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

How to save changes from DataGridView to the database?

I would like to save the changes made to a DataGridView into the database MS SQL CE,
but i can't, the changes are not saved to the database....
This the code (VB.net):
Private Sub Form1_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) handles MyBase.Load
Dim con As SqlCeConnection = New SqlCeConnection(#"Data Source=C:\Users\utente\Documents\test.sdf")
Dim cmd As SqlCeCommand = New SqlCeCommand("SELECT * FROM mytable", con)
con.Open()
myDA = New SqlCeDataAdapter(cmd)
Dim builder As SqlCeCommandBuilder = New SqlCeCommandBuilder(myDA)
myDataSet = New DataSet()
myDA.Fill(myDataSet, "MyTable")
DataGridView1.DataSource = myDataSet.Tables("MyTable").DefaultView
con.Close()
con = Nothing
End Sub
Private Sub edit_rec()
Dim txt1, txt2 As String
Dim indice As Integer = DataGridView1.CurrentRow.Index
txt1 = DataGridView1(0, indice).Value.ToString '(0 is the first column of datagridview)
txt2 = DataGridView1(1, indice).Value.ToString '(1 is the second) MsgBox(txt1 + " " + txt2)
'
DataGridView1(0, indice).Value = "Pippo"
DataGridView1(1, indice).Value = "Pluto"
'
Me.Validate()
Me.myDA.Update(Me.myDataSet.Tables("MyTable"))
Me.myDataSet.AcceptChanges()
'
End Sub
Thank you for any suggestion.
You need to use myDA.Update, that will commit the changes. This is because any changes that you are making are made in the local instance of that dataset. And therefore disposed of just like any other variable.
... I can see that in your edit_rec sub, but what is calling that - there is nothing in the code that you have posted.
A little late perhaps.
In the Form load event, you open and close the connection.
And furthermore, all are local variables who loose any value or data when leaving the sub
Public Class Form1
Dim con As SqlCeConnection
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
con = New SqlCeConnection(#"Data Source=C:\Users\utente\Documents\test.sdf")
Dim cmd As SqlCeCommand = New SqlCeCommand("SELECT * FROM mytable", con)
con.Open()
myDA = New SqlCeDataAdapter(cmd)
Dim builder As SqlCeCommandBuilder = New SqlCeCommandBuilder(myDA)
myDataSet = New DataSet()
myDA.Fill(myDataSet, "MyTable")
DataGridView1.DataSource = myDataSet.Tables("MyTable").DefaultView
cmd.Dispose()
End Sub
***Put the closing of connection here instead or somewhere else suitable when you don't use it anymore***
Private Sub Form1_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
con.Close()
con = Nothing
End Sub
Private Sub edit_rec()
Dim txt1, txt2 As String
Dim indice As Integer = DataGridView1.CurrentRow.Index
txt1 = DataGridView1(0, indice).Value.ToString '(0 is the first column of datagridview)
txt2 = DataGridView1(1, indice).Value.ToString '(1 is the second) MsgBox(txt1 + " " + txt2)
'
DataGridView1(0, indice).Value = "Pippo"
DataGridView1(1, indice).Value = "Pluto"
'You code to update goes here and not in my scope of answer
End Sub
End Class
I think you want to add # with your connection string
SqlConnection con;
con = New SqlConnection(#"Data Source=C:\Users\utente\Documents\test.sdf");