Find a part of text in a listbox - vb.net

I've been given some code to find text that is contained in a listbox but, its not what I need. When the user types in the textbox (which is the search field), they have to type the exact text, not the part of the text. Is there any way to find a part of a value/text in a listbox?
For example, I have a listbox that contains these items:
data1
data2
When I type (2) in the search field(textbox/richtextbox), I would like the second item, which contain the '2' value, to be selected.
How can I code this?

You could use IndexOf
Dim hits = From item In listBox1.Items.Cast(Of String)()
Where item.IndexOf(txtSearch.Text, StringComparison.OrdinalIgnoreCase) >= 0
If hits.Any Then
listBox1.SelectedItem = hits.First()
End If
If you don't want to ignore the case, just use String.Contains instead of String.IndexOf.
Note that above is a linq query, so it won't work with .NET 2 this way.

You have to know the terms you want for your search. For example, Text containing any of the letters in the search text, complete words, not searching symbols, etc.
You have to do it "manually", there isnt a function to search similar texts.
For example:
Private Sub SearchBox_TextChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles SearchBox.TextChanged
Dim iFound As Integer = -1
For i As Integer = 0 To SearchBox.TextLength - 1
If TextBox1.Text.Contains(SearchBox.Text(i)) Then
iFound = TextBox1.Text.IndexOf(SearchBox.Text(i))
Exit For
End If
Next
If iFound >= 0 Then
TextBox1.Select(iFound, 1)
End If
End Sub

You didn't mention that you want to keep other items (which do not match with the search query) in your listbox or not.
If you just want to keep the items in listbox which matches or contains your search query then you can check this answer on stackoverflow.
Match starting of a string in listbox OR Match some part of a string in listbox items

Related

Single selection CheckedListBox control

I have a CheckedListBox control.I want to limit it's selection property to one means now a user can select more than one item in the control, need to limit this property to single selection only.
For example, Let's CHKListsolutions has following items
Google
Bing
Yahoo
Normally we can select 3 of them because of an obvious reason.
How to make this CHKListsolutions to select only one item in the list.
for example, I select Google and for some reason I want chnage the selection so I will select Yahoo then my last selection should unchecked and new one should be checked
I have checked in the resource for a property but in vain.
Any help would be very much appreciated
Private Sub CHKListsolutions_MouseClick(sender As Object, e As MouseEventArgs) Handles CHKListsolutions.MouseClick
Dim idx, sidx As Integer
sidx = CHKListsolutions.SelectedIndex
For idx = 0 To CHKListsolutions.Items.Count - 1
If idx <> sidx Then
CHKListsolutions.SetItemChecked(idx, False)
Else
CHKListsolutions.SetItemChecked(sidx, True)
End If
Next
End Sub
In MouseClick event you'll get the currently selected index of the item in the control(sidx) use this sidx to loop through number of items in the control and uncheck checked item that is not equal to the current index using SetItemChecked method
Use Radio Button instead of Checkedlistbox

I was trying to Change the row color in DataGridView based on the quantity of a cell value but first row doesn't change [duplicate]

I am using vb.net and I have data coming into my DGV and I have a column labeled deployed if it's a '1', I want to have all the rows with '1' in the deployed column RED and if it's a '0', I want all the rows to be GREEN. This is my method I have, right now the column is the 10th column but it doesn't like the = operator. Even when I use quotes on the 1 with equals compare operator for strings. Should be an integer but I was trying every way I could to see why it's not working.
Private Sub LaptopGrid_CellFormatting(ByVal Sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles LaptopGrid.CellFormatting
For i As Integer = 0 To LaptopGrid.Rows.Count - 1
If LaptopGrid.Rows(i).Cells(9).Value = 1 Then
LaptopGrid.RowsDefaultCellStyle.BackColor = Color.Green
End If
Next
End Sub
There are a couple of issues with your code.
First, you are handling the CellFormatting event but you are iterating every row to set the backcolor. That event is meant for you to do something to a single, specific cell, the one in question is indicated in the event args: e.RowIndex and e.ColumnIndex. Using a loop, you are acting on many more rows than needed and doing so over and over.
Second, VB has data types. Int32 is one type, String is another, and Object is yet another. You need to convert one type to the other type before you compare. LaptopGrid.Rows(r).Cells(c).Value returns Object (since a cell can literally hold anything), so to compare to 1 you need to convert it to integer.
Finally, you may not want the CellFormatting event for this. If the cell in question is not on screen, the event wont fire (perhaps the user resized the columns). RowPrePaint on the other hand will fire when the row scrolls into view.
Private Sub dgv1_RowPrePaint(sender As Object,
e As DataGridViewRowPrePaintEventArgs) Handles dgv1.RowPrePaint
' dont do the NewRow
If e.RowIndex < 0 OrElse dgv1.Rows(e.RowIndex).IsNewRow Then Return
' convert to int32, then compare
' act on just this row - e.RowIndex
If Convert.ToInt32(dgv1.Rows(e.RowIndex).Cells(3).Value) > 3 Then
dgv1.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.LemonChiffon
Else
dgv1.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.MistyRose
End If
End Sub
If the user can edit that cell value, you will want to update the back color accordingly.

vb.net Search for Full or partial match in Datagridview from TextBox and select the first match while displaying the full datagrid

I have a customers table that is displayed in a datagridview. I would like the user to be able to enter the customers full or partial last name and click a buttom that would then find the first customer that met the match in the text box. As an example: The user types "wil" into the text box and the first record found is for "williams" even though the user is looking for "wilson". The record would be highlighted(selected) and the user could scroll to look at other records and select "wilson" manually (the manual part I can code).
I have searched for hours on the internet and cannot find this type of code. Most of it is filtering or searching every cell and returning every value.
I am currently reworking a project I did with an access database and vba several years ago. I had thought vb.net would be very similar but it is not similar enough for me to modify this code. I'm also going to use a sql database.
The index field is obviously cell(0) and last name is cell(1).
I have found a solution although I did have to modify it. It will do everything I need except one thing. If I type the letter "H" and do a search on last name, it finds the first lastname that has an "H" in the last name but in a different position from the first letter. I need it to go to the first last name that begins with an "H". I have listed my code below.
Dim srch As String
Dim irowindex As Integer
Dim strl As Integer
srch = txtSearch.Text
dgvCustomers.ClearSelection()
For i As Integer = 0 To dgvCustomers.Rows.Count - 1
If dgvCustomers.Rows(i).Cells(0).Value IsNot Nothing Then
If dgvCustomers.Rows(i).Cells(1).Value.ToString.ToUpper.Contains(srch.ToUpper) Then
dgvCustomers.Rows(i).Selected = True
dgvCustomers.RowsDefaultCellStyle.SelectionBackColor = Color.DimGray
irowindex = dgvCustomers.SelectedCells.Item(0).Value
MessageBox.Show(irowindex)
Exit For
End If
End If
Next
End Sub
try this sir.
for each row as datagridviewrow in nameofdatagrid.rows
if row.cells("Lastname").value = txtbox.text then
nameofdatagrid.clearselection()
row.cells("Lastname").selected = true
exit for
end if
next
I think this is your problem? finding lastname match in the datagrid and select it?
hope this will help you :)
Dim srch As String
Dim irowindex As Integer
Dim strl As Integer
srch = txtSearch.Text
dgvCustomers.ClearSelection()
For i As Integer = 0 To dgvCustomers.Rows.Count - 1
If dgvCustomers.Rows(i).Cells(0).Value IsNot Nothing Then
If dgvCustomers.Rows(i).Cells(1).Value.ToString.ToUpper.StartsWith(srch.ToUpper) Then
dgvCustomers.Rows(i).Selected = True
dgvCustomers.RowsDefaultCellStyle.SelectionBackColor = Color.DimGray
irowindex = dgvCustomers.SelectedCells.Item(0).Value
MessageBox.Show(irowindex)
Exit For
End If
End If
Next

Search Listbox and return specific number of items defined in another field - VB.net

I'm running a search query that pulls the search string from one text box, then searches a listbox for the string and displays the results in a second listbox. I would like to define the number of items that it returns based on a second text box. So far I am able to get all list items with be given string to show in the second box. But I have yet to get it to limit the search to 1 item etc. The functional code I've used to show all results is:
Private Sub btnGo_Click(sender As Object, e As EventArgs) Handles btnGo.Click
lstResults.Items.Clear()
If txtSearch.Text.Length > 0 Then
For index As Integer = 0 To lstCountries.Items.Count - 1
Dim txt = lstCountries.Items(index).ToString()
If txt.StartsWith(txtSearch.Text, StringComparison.CurrentCultureIgnoreCase) Then
lstResults.Items.Add(txt)
End If
Next
End If
I've tried using while txtnumber.text > 1 then ahead of this but seem to have created a loop. Any ideas as to what I'm missing?
The datasource is going to have the final say on how many results there are. If the user specifies 3 and there are only 2 in the source, thats all you will get. Something like this will move the results from one to the other until the max is found:
Dim Max as integer = Convert.Toint32(txtNumber.Text)
Dim Count as integer = 0
lstResults.Items.Clear()
For index As Integer = 0 To lstCountries.Items.Count - 1
if lstCountries.Items(index).StartsWith(txtSearch.Text, StringComparison.CurrentCultureIgnoreCase) Then
lstResults.Items.Add(lstCountries.Items(index))
count += 1
end if
' exit the loop if we found enough
If count>= Max Then
Exit For
End If
Next
If the listbox just contains text (strings) then you do not need the ToString: lstCountries.Items(index).StartsWith(strSearch). Basically, you need to exit the loop once the user desired number have been found OR if you run out of data...if I understood right. while txtnumber.text > 1 would not work because textboxes contain strings not numerics (23 is not the same as "23").
The LINQ extensions would work well here as well:
lstResults.Items.AddRange((From item In lstCountries.Items
Let strItem As String = item.ToString
Where strItem.StartsWith(txtSearch.Text, StringComparison.CurrentCultureIgnoreCase)
Select strItem).Take(Integer.Parse(txtnumber.Text)).ToArray)
This assumes that all your data has already been validated.

How to merge two multiline textboxes

I need to combine two multi-line textboxes in vb net, like this:
textbox1:
a
b
c
d
textbox2:
1
2
3
4
textbox3:
a1
b2
c3
d4
Just a form with three textboxes. And a button to merge/combine/concatenate each value from t1 and t2, in t3.
One of my attempts:
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
For Each line In TextBox1.Lines
For Each linex In TextBox2.Lines
Me.TextBox3.Text += line & linex
Me.TextBox3.Text += Environment.NewLine
Next
Next
End Sub
but result combination of lines (lines=linex) taken by two (a1,a2,a3,b1,b2,b3...)
There are probably many ways you could do this. I have shown you one below but you would be assuming that textbox two contains the same amount of lines as textbox 1. It doesnt contain any validation but would do what you are asking.
See the comments to understand what is happening.
'Declare empty string for concatinating the text used in textbox 3
Dim lsText As String = String.Empty
'Loop for the count of lines in the textbox starting at an index of 0 for pulling data out
For i As Integer = 0 To TextBox1.Lines.Count - 1
'Check if lsText has already been assigned a value
If lsText = String.Empty Then
'If is has not then you know its the first so dont need a carriage return line feed simply take both values at that index
lsText = TextBox1.Lines(i) & TextBox2.Lines(i)
Else
'Otherwise you want the new value on a new line
lsText = lsText & vbCrLf & TextBox1.Lines(i) & TextBox2.Lines(i)
End If
Next
'Set the textbox text to the finished concatination
TextBox3.Text = lsText
I would use an integer as a counter in a loop that will extract the letter from each at the value of count, and increase count each time.
What you are trying to do is quite simple, so i won't provide any code - You won't learn efficiently that way.
Just know that you will need to filter newlines, know how many 'char' in each textbox, and use a loop.
Or many other ways, but i think what i have hinted is easy and should be about 5 lines of code that you have somewhat already demonstrated.
Good luck. keep posting what you are trying, and i'll give help if i feel you are trying. Though now i'm going to bed.