vb2008 search through listbox using textbox - vb.net

hi I have a form that find, or should I say filter, the items in a listbox using a textbox. I have a textbox used for searching and a listbox populated with items from database. Now, say listbox items include apple, banana, berry, cashew, lemon, mango, peanut. If I typed 'b' on the textbox, listbox only show banana and berry..if I typed 'ba' then listbox only show banana but if I typed 'be' then it shows berry and so on. I already got this working (with the code marked as commented in the txtSearch event). My problem is that how can I bring the items in the listbox back when the user strike the backspace? Because, say I have banana and berry in the listbox now, when I erased the text that I typed in the textbox it should list back all the items again so that if I want to search another item it will be filtered again. thanks in advance.
Code Update
Public Class Glossary
Private Sub Glossary_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Call List()
Refreshlist()
End Sub
Private Sub List()
Dim myCmd As New MySqlCommand
Dim myReader As MySqlDataReader
Dim myAdptr As New MySqlDataAdapter
Dim myDataTable As New DataTable
Call Connect()
With Me
STRSQL = "Select word from glossary"
Try
myCmd.Connection = myConn
myCmd.CommandText = STRSQL
myReader = myCmd.ExecuteReader
If (myReader.Read()) Then
myReader.Close()
myAdptr.SelectCommand = myCmd
myAdptr.Fill(myDataTable)
lstword.DisplayMember = "word"
lstword.ValueMember = "word"
If myDataTable.Rows.Count > 0 Then
For i As Integer = 0 To myDataTable.Rows.Count - 1
lstword.Items.Add(myDataTable.Rows(i)("word"))
Next
End If
End If
'lstword.Items.Clear()
'lstword.Items.AddRange(word.Where(Function(word) word.ToString().Contains(txtSearch.Text)).ToArray())
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
myReader = Nothing
myCmd = Nothing
myConn.Close()
Call Disconnect()
End With
End Sub
Dim word As List(Of Object)
Private Sub Refreshlist()
lstword.Items.Clear()
lstword.Items.AddRange(word.Where(Function(word) word.ToString().Contains(txtSearch.Text)).ToArray())
End Sub
Private Sub txtSearch_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSearch.TextChanged
lstword.Items.Clear()
lstword.Items.AddRange(word.Where(Function(word) word.ToString().Contains(txtSearch.Text)).ToArray())
Refreshlist()
'Call List()
'lstword.BeginUpdate()
'Try
' ' keep track of the "non-searched items" '
' Dim word As New List(Of Object)
' lstword.SelectedIndices.Clear()
' If txtSearch.Text.Length > 0 Then
' For index As Integer = 0 To lstword.Items.Count - 1
' Dim item As String = lstword.Items(index).ToString()
' If item.IndexOf(txtSearch.Text, StringComparison.CurrentCultureIgnoreCase) >= 0 Then
' lstword.SelectedIndices.Add(index)
' Else
' ' this item was not searched for; we will remove it '
' word.Add(index)
' End If
' Next
' ' go backwards to avoid problems with indices being shifted '
' For i As Integer = word.Count - 1 To 0 Step -1
' Dim indexToRemove As Integer = word(i)
' lstword.Items.RemoveAt(indexToRemove)
' Next
' End If
'Finally
' lstword.EndUpdate()
'End Try
End Sub
End Class

The first step is to store the items in off-screen memory. For instance:
Dim words As List(Of Object)
Then when you refresh the list box, only populate it with the items from that in-memory list which match the current criteria:
lstword.Items.Clear()
lstword.Items.AddRange(
words.FindAll(
Function(word) Return word.ToString().Contains(txtSearch.Text)
).ToArray()
)
Or, using LINQ:
lstword.Items.Clear()
lstword.Items.AddRange(
words.Where(
Function(word) word.ToString().Contains(txtSearch.Text)
).ToArray()
)
UPDATE
Since you seem to be having trouble getting it working, and it's hard to say what's wrong with your code without actually seeing it, here's a complete working example:
Public Class Form1
Dim words As New List(Of Object)(New String() {"apple", "banana", "berry", "cashew", "lemon", "mango", "peanut"})
Private Sub RefreshList()
lstword.Items.Clear()
lstword.Items.AddRange(
words.Where(
Function(word) word.ToString().Contains(txtSearch.Text)
).ToArray()
)
End Sub
Private Sub txtSearch_TextChanged(sender As Object, e As EventArgs) Handles txtSearch.TextChanged
RefreshList()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
RefreshList()
End Sub
End Class
UPDATE 2
I tried using your code with my recommended suggestions and it worked fine. Here's the code that worked for me. Try it and let me know if it doesn't work for you:
Public Class Glossary
Private Sub Glossary_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
List()
Refreshlist()
End Sub
Private Sub List()
word.AddRange(New String() {"apple", "banana", "berry", "cashew", "lemon", "mango", "peanut"})
End Sub
Private word As New List(Of Object)()
Private Sub Refreshlist()
lstword.Items.Clear()
lstword.Items.AddRange(word.Where(Function(word) word.ToString().Contains(txtSearch.Text)).ToArray())
End Sub
Private Sub txtSearch_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSearch.TextChanged
Refreshlist()
End Sub
End Class
If that works, then all you need to do is change the List method to load from the database instead of being a hard-coded list.

Get your initial list off the database, pop it in a List class e.g List.
The use your search text to select all the matching items and put them in the list box. Blank search text you just put all of them in.
You might want to have a look at Foreach and List.FindAll as well.

Related

Coding navigation buttons using vb.net 2012

My main goal is to code navigation buttons to control records of a vb.net project connected with Microsoft Access Database. The four buttons included are First record, Last record, Next record and Previous record. The errors showing say "ShowData" and "CurrentRow" are not declared.
CurrentRow shows the following error correction options:
ShowData shows the following error correction options:
'to navigate to first record
Private Sub btn_first_Click(sender As Object, e As EventArgs) Handles btn_first.Click
CurrentRow = 0
ShowData(CurrentRow)
End Sub
'to navigate to last record
Private Sub btn_last_Click(sender As Object, e As EventArgs) Handles btn_last.Click
CurrentRow = Dst.Tables("Purchases_file").Rows.Count - 1
ShowData(CurrentRow)
End Sub
'to navigate to previous record
Private Sub btn_previous_Click(sender As Object, e As EventArgs) Handles btn_previous.Click
If CurrentRow <> 0 Then
CurrentRow -= 1
ShowData(CurrentRow)
Else
MsgBox("First record is reached!", MsgBoxStyle.Exclamation)
End If
End Sub
'to navigate to next record
Private Sub btn_next_Click(sender As Object, e As EventArgs) Handles btn_next.Click
If CurrentRow = Dst.Tables("Purchases_file").Rows.Count - 1 Then
MsgBox("Last record is reached!", MsgBoxStyle.Exclamation)
Else
CurrentRow += 1
ShowData(CurrentRow)
End If
End Sub
According to the error you get you did not declare CurrentRow before using it in the methods. Put
Private CurrentRow as Integer
in your class. ShowData calls the method to retrieve the data from the database. It should be something like this:
Private Sub ShowData(byval row as integer)
'code to get the data in the database
End Function
If the variable and method exist in another class of the project you need to reference them via their class. For example:
ClassName.CurrentRow
ClassName.ShowData(CurrentRow)
My Roasters table has field names of Name, City, and Zip. They are bond to labels on the BindingNavigator form and also a DataGridView. The BindingNavigator provides the buttons you describe.
Imports System.Data.SqlClient
Public Class BindingNavigator
Dim WithEvents bindSrc As New BindingSource
Private Sub BindingNavigator_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dt = LoadData1()
bindSrc.DataSource = dt
BindingNavigator1.BindingSource = bindSrc
lblItem.DataBindings.Add(New Binding("Text", bindSrc, "Name"))
lblDescription.DataBindings.Add(New Binding("Text", bindSrc, "City"))
lblPrice.DataBindings.Add(New Binding("Text", bindSrc, "Zip"))
DataGridView1.DataSource = bindSrc
End Sub
Private Function LoadData1() As DataTable
Dim dt As New DataTable
Using conn As New SqlConnection(My.Settings.CoffeeConnection),
cmd As New SqlCommand("Select Top 10 * From Roasters;", conn)
conn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
End Class

Passing data through form with showdialog but without closing event

I have a first form (form_notice_hashtag) called like this:
Public Sub afficher_hashtag(hashtag As String, plateforme_hashtag As String)
Dim form_notice_hashtag_1 As New form_notice_hashtag
form_notice_hashtag_1.StartPosition = FormStartPosition.CenterScreen
form_notice_hashtag_1.Show()
End Sub
In form_notice_hashtag_1, i have a button calling a 2nd form (form_recherche_thesaurus) like this:
Private Sub hashtag_thesaurus_search_button_Click(sender As Object, e As EventArgs) Handles hashtag_thesaurus_search_button.Click
Dim form_recherche_thesaurus_1 As New form_recherche_thesaurus With {
.StartPosition = FormStartPosition.Manual,
.Location = New Point(Me.Left + Me.Width, Me.Top)
}
form_recherche_thesaurus_1.ShowDialog(Me)
End Sub
In form_recherche_thesaurus, i have a datagridview listing some words. The user can select one word, then by clicking a button in form_recherche_thesaurus, the word which will be added to a textbox in form_notice_hashtag
Private Sub thesaurus_ok_button_Click(sender As Object, e As EventArgs) Handles thesaurus_ok_button.Click
Dim list_terms_array As String()
Select Case Owner.Name.ToString
Case "form_notice_hashtag"
list_terms_array = Split(Remove_Duplicates_From_Strings_With_SemiColon(form_notice_hashtag.hashtag_descripteurs_txtbox.Text & ";" & selected_term), ";")
form_notice_hashtag.hashtag_descripteurs_txtbox.Text = (String.Join(";", list_terms_array.Where(Function(s) Not String.IsNullOrEmpty(s))))
End Select
End Sub
I used a select because this mechanism would be used in the same way with other forms than form_notice_hashtag.
Problem: the textbox in form_notice_hashtag is not filled with the selected keywords. I guess it's because of the way form_notice_hashtag is called.
I can't use the solution as explained here Send values from one form to another form because i understood (maybe badly) that this solution works only if the 2nd form (form_recherche_thesaurus in my case) is closed (i.e closing was the trigger) which i don't want.
How can I proceed?
Thanks to jmcilhinney and this page of his blog, here is the solution that allows to transfer several data from a called form (form_recherche_thesaurus) to a calling form (form_notice_hashtag) without closing the called form .
Public Class form_notice_hashtag
Private WithEvents form_recherche_thesaurus_1 As form_recherche_thesaurus
Private selected_thesaurus_term As String
Private Sub form_recherche_thesaurus_1_TextBoxTextChanged(sender As Object, e As EventArgs) Handles form_recherche_thesaurus_1.TextBoxTextChanged
Dim list_terms_array As String() = Split(Remove_Duplicates_From_Strings_With_SemiColon(Me.hashtag_descripteurs_txtbox.Text & ";" & form_recherche_thesaurus_1.selected_term), ";")
Me.hashtag_descripteurs_txtbox.Text = (String.Join(";", list_terms_array.Where(Function(s) Not String.IsNullOrEmpty(s))))
End Sub
Private Sub hashtag_thesaurus_search_button_Click(sender As Object, e As EventArgs) Handles hashtag_thesaurus_search_button.Click
Dim form_recherche_thesaurus_1 As New form_recherche_thesaurus With {
.StartPosition = FormStartPosition.Manual,
.Location = New Point(Me.Left + Me.Width, Me.Top)
}
If Me.form_recherche_thesaurus_1 Is Nothing OrElse Me.form_recherche_thesaurus_1.IsDisposed Then
Me.form_recherche_thesaurus_1 = New form_recherche_thesaurus With {
.StartPosition = FormStartPosition.Manual,
.Location = New Point(Me.Left + Me.Width, Me.Top)
}
Me.form_recherche_thesaurus_1.Show()
End If
Me.form_recherche_thesaurus_1.Activate()
End Sub
End Class
Public Class form_recherche_thesaurus
Public Event TextBoxTextChanged As EventHandler
Private term_thesaurus As String
Public Property selected_term() As String
Get
Return term_thesaurus
End Get
Set(ByVal value As String)
term_thesaurus = value
End Set
End Property
Private Sub thesaurus_ok_button_Click(sender As Object, e As EventArgs) Handles thesaurus_ok_button.Click
Dim list_terms_array As String()
Me.selected_term = Me.thesaurus_search_results_datagrid.Item(0, Me.thesaurus_search_results_datagrid.CurrentRow.Index).Value
Me.DialogResult = DialogResult.OK
RaiseEvent TextBoxTextChanged(Me, EventArgs.Empty)
End Sub

Shuffle the contents of Text Boxes

I'm trying to get 10 different inputs in TextBoxes to be displayed in a randomized order.
I split 2 processes to make it easier to understand:
Button puts numbers in random orders from 1-10(works)
Button should replace the numbers with the contents of the TextBoxes(doesn't work)
Here is the GUI
/ Here is the code:
Public tblRandom As New DataTable
Private Sub btnRandom_Click(sender As Object, e As EventArgs) Handles btnGo.Click
Dim r As New Random
Dim tblRandom As New DataTable
tblRandom.Columns.Add("Order")
tblRandom.Constraints.Add("pk", tblRandom.Columns(0), True)
While tblRandom.Rows.Count < 10
Dim newrow As Object = r.Next(10) + 1
Try
tblRandom.Rows.Add(CStr(newrow))
Catch ex As Exception
End Try
End While
dgvRandom.DataSource = tblRandom
End Sub
Private Sub btnReplace_Click(sender As Object, e As EventArgs) Handles btnReplace.Click
For Each row As DataGridViewRow In dgvRandom.Rows
For Each cell As DataGridViewCell In row.Cells
If cell.Value IsNot Nothing Then
Dim i As Integer = 0
While i < 10
i += 1
If cell.Value.ToString = i Then
cell.Value = ActiveControl.Tag(i)
End If
End While
End If
Next
Next
dgvRandom.DataSource = tblRandom
End Sub
End Class
My understanding of your goal here is to take the text in 10 textboxes and shuffled their content. The DataGrid seems to be a temporary location that you're using during the shuffle.
There's a much easier way that avoids all that. Try this code:
Private _random = New Random()
Private Sub BtnRandom_Click(sender As Object, e As EventArgs) Handles btnRandom.Click
Dim tbs As TextBox() = {TextBox1, TextBox2, TextBox3, TextBox4, TextBox5, TextBox6, TextBox7, TextBox8, TextBox9, TextBox10}
Dim text = tbs.Select(Function(tb) tb.Text).OrderBy(Function(t) _random.Next()).ToList()
For Each x In tbs.Zip(text, Function(tb, t) New With {.tb = tb, .t = t})
x.tb.Text = x.t
Next
End Sub
That's it. Job done.
If you still need the DataGrid it would be easy to add a further line just after the x.tb.Text = x.t that adds the content of x.t to the grid.
For the first part you can do:
Public tblRandom As DataTable
Private ReadOnly rand As New Random
Private Sub btnRandom_Click(sender As Object, e As EventArgs) Handles btnRandom.Click
tblRandom?.Dispose()
tblRandom = New DataTable
tblRandom.Columns.Add("Order")
tblRandom.Constraints.Add("pk", tblRandom.Columns(0), True)
Dim nums As New List(Of Integer)
While nums.Count < 10
Dim num = rand.Next(1, 11)
If Not nums.Contains(num) Then
nums.Add(num)
End If
End While
nums.ForEach(Sub(n) tblRandom.Rows.Add(n))
dgvRandom.DataSource = tblRandom
End Sub
As for the second part, you just need to do:
Private Sub btnReplace_Click(sender As Object, e As EventArgs) Handles btnReplace.Click
For Each row As DataRow In tblRandom.Rows
'Assuming the text boxes are hosted by the Form.
Dim txt = Me.Controls.OfType(Of TextBox).
Where(Function(x) x.Tag?.ToString = row(0).ToString).
FirstOrDefault
If txt IsNot Nothing Then
row(0) = txt.Text
End If
Next
tblRandom.AcceptChanges()
End Sub
You are getting the tag from the ActiveControl
cell.Value = ActiveControl.Tag(i)
but as you've just clicked the Replace button, isn't that the active control?

if the file not exits then return no error vb

I have start this application every things its work fine but i have a small bug but i can not find the solution to solve the error.
i have debug it and the error its because the file not exist
is there any way to me to populate my datagridview with all *.gif images From a directory and the check if its null or some thing like that.
What i mean is is there any way to my to populate all gif images found on the chose Directory?
in fact i have all ready try like this but i get one error "Provided column already belongs to the DataGridView control.
Well finaly i have found a solution to load all images from a directory to a datagridview programmatic
Here Is The Working Code
Public Class Form5
Private Sub addBtn_Click(sender As Object, e As EventArgs) Handles addBtn.Click
'Populate()
ShowImages()
End Sub
'CLEAR DATAGRIDVIEW
Private Sub clearBtn_Click(sender As Object, e As EventArgs) Handles clearBtn.Click
DataGridView1.Rows.Clear()
End Sub
'WHEN AN IMAGE IS CLICKED
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
MessageBox.Show("You Clicked Image At Col: " + e.ColumnIndex.ToString() + " Row: " + e.RowIndex.ToString())
End Sub
Private Sub Form5_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Public Sub ShowImages()
Dim directory As New System.IO.DirectoryInfo("C:\avitogifconverter\")
If directory.Exists Then
Dim pngFiles() As System.IO.FileInfo = directory.GetFiles("*.gif")
For Each pngFile As System.IO.FileInfo In pngFiles
If pngFile.Exists Then
Dim image = System.Drawing.Image.FromFile(pngFile.FullName)
Using image
Dim count = 1
' do something with the image like show in picture box
'CONSTRUCT IMG COLUMN
Dim imgCol As DataGridViewImageColumn = New DataGridViewImageColumn()
imgCol.HeaderText = "Photo"
imgCol.Name = "Col 1"
DataGridView1.Columns.Add(imgCol)
'CONSTRUCT ROWS
'FIRST ROW
Dim img As Image = System.Drawing.Image.FromFile(pngFile.FullName)
Dim row As Object() = New Object() {img, img, img}
DataGridView1.Rows.Add(row)
End Using
End If
Next
End If
End Sub
End Class
Using Directory.EnumerateFiles, you could do something like this:
Dim row = New List(Of Image)(3)
For Each filename In Directory.EnumerateFiles("C:\avitogifconverter", "*.gif")
row.Add(Image.FromFile(filename))
If row.Count = 3 Then
DataGridView1.Rows.Add(row.ToArray())
row.Clear()
End If
Next
If row.Count > 0 Then
DataGridView1.Rows.Add(row.ToArray())
row.Clear()
End If

Pass variable to new form with Datatable and Listbox

I am currently trying to write an application like address book. Listbox works properly, it shows everything corretly. But I need to pass id of chosen listbox item to another form. I got code like this in Form2:
Private myTable As New DataTable()
Public Sub LoadXml(sender As Object, e As EventArgs) Handles Me.Load
With myTable.Columns
.Add("DisplayValue", GetType(String))
.Add("HiddenValue", GetType(Integer))
End With
myTable.DefaultView.Sort = "DisplayValue ASC"
ListBox1.DisplayMember = "DisplayValue"
ListBox1.ValueMember = "HiddenValue"
ListBox1.DataSource = myTable
Dim doc As New Xml.XmlDocument
doc.Load("c:\address.xml")
Dim xmlName As Xml.XmlNodeList = doc.GetElementsByTagName("name")
Dim xmlSurname As Xml.XmlNodeList = doc.GetElementsByTagName("surname")
Dim xmlId As Xml.XmlNodeList = doc.GetElementsByTagName("id")
For i As Integer = 0 To xmlName.Count - 1
Dim nazwa As String = xmlName(i).FirstChild.Value + " " + xmlSurname(i).FirstChild.Value
myTable.Rows.Add(nazwa, xmlId(i).FirstChild.Value)
MsgBox(myTable.Rows(i).Item(1).ToString)
Next i
ListBox1.Sorted = True
End Sub
Later in the code I have event:
Public Sub ListBox1_DoubleClick(sender As Object, e As EventArgs) Handles ListBox1.DoubleClick
End Sub
I would like to know how can I call id from DataTable for selected listbox item. I hope u understand what I mean since my english is not perfect :)
Since you have added the XML value id to the data table column HiddenValue and you have assigned HiddenValue as the ValueMember for the listbox, once a record is selected in the listbox, id will be available in the listbox's [SelectedValue][1] member. For example:
Public Sub ListBox1_DoubleClick(sender As Object, e As EventArgs) Handles ListBox1.DoubleClick
MsgBox("Selected Id: " & ListBox1.SelectedValue.ToString())
End Sub