VB.NET Search ListBox for string and return specific data - vb.net

I have a populated listbox. Each item has a string of data with id's and values. How would i search for the id and receive the vale?
If i search for 'itemColor' i would like it to return each boot color in a new msgbox.
itemName="boots" itemCost="$39" itemColor="red"
itemName="boots" itemCost="$39" itemColor="green"
itemName="boots" itemCost="$39" itemColor="blue"
itemName="boots" itemCost="$39" itemColor="yellow"
I understand there are different and easier ways to do this but i need to do it this way.
Thanks!

Here's one way to do it involving parsing the text as XML:
' Here's Some Sample Text
Dim listboxText As String = "itemName=""boots"" itemCost=""$39"" itemColor=""red"""
' Load XML and Convert to an Object
Dim xmlDocument As New System.Xml.XmlDocument
xmlDocument.LoadXml("<item " & listboxText & "></item>")
Dim item = New With {.ItemName = xmlDocument.DocumentElement.Attributes("itemName").Value,
.ItemCost = xmlDocument.DocumentElement.Attributes("itemCost").Value,
.ItemColor = xmlDocument.DocumentElement.Attributes("itemColor").Value}
' Write It Out as a Test
Console.WriteLine(item.ItemName & " " & item.ItemCost & item.ItemColor)
Console.Read()

Create a class (or structure), the appropriate properties, a default constructor, a parametized constructor and an Override of .ToString.
Public Class Item
Public Property Name As String
Public Property Cost As String
Public Property Color As String
Public Sub New()
End Sub
Public Sub New(sName As String, sCost As String, sColor As String)
Name = sName
Cost = sCost
Color = sColor
End Sub
Public Overrides Function ToString() As String
Return $"{Name} - {Cost} - {Color}"
End Function
End Class
Item objects are added to the list box calling the parameterized constructor. The list box calls .ToString on the objects to determine what to display.
Private Sub FillList()
ListBox3.Items.Add(New Item("boots", "$39", "red"))
ListBox3.Items.Add(New Item("boots", "$39", "green"))
ListBox3.Items.Add(New Item("boots", "$39", "blue"))
ListBox3.Items.Add(New Item("boots", "$39", "yellow"))
End Sub
Since we added Item objects to the list box, we can cast each list item back to the Item type and access its properties.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim sb As New StringBuilder
For Each i In ListBox3.Items
sb.AppendLine(DirectCast(i, Item).Color)
Next
MessageBox.Show(sb.ToString)
End Sub

Related

Multiple Search Criteria (VB.NET)

So my problem is:
I have a List of a custom Type {Id as Integer, Tag() as String},
and i want to perform a multiple-criteria search on it; eg:
SearchTags={"Document","HelloWorld"}
Results of the Search will be placed a ListBox (ListBox1) in this format:
resultItem.id & " - " & resultItem.tags
I already tried everything i could find on forums, but it didn't work for me (It was for db's or for string datatypes)
Now, i really need your help. Thanks in advance.
For Each MEntry As EntryType In MainList
For Each Entry In MEntry.getTags
For Each item As String In Split(TextBox1.Text, " ")
If Entry.Contains(item) Then
If TestIfItemExistsInListBox2(item) = False Then
ListBox1.Items.Add(item & " - " & Entry.getId)
End If
End If
Next
Next
Next
Example Custom Array:
(24,{"snippet","vb"})
(32,{"console","cpp","helloworld"})
and so on...
I searched for ("Snippet vb test"):
snippet vb helloWorld - 2
snippet vb tcpchatEx - 16
cs something
test
So, i'll get everything that contains one of my search phrases.
I expected following:
snippet vb tcp test
snippet vb dll test
snippet vb test metroui
So, i want to get everything that contains all my search phrases.
My entire, code-likely class
Imports Newtonsoft.Json
Public Class Form2
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Dim MainList As New List(Of EntryType)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MainList.Clear()
Dim thr As New Threading.Thread(AddressOf thr1)
thr.SetApartmentState(Threading.ApartmentState.MTA)
thr.Start()
End Sub
Delegate Sub SetTextCallback([text] As String)
Private Sub SetTitle(ByVal [text] As String) ' source <> mine
If Me.TextBox1.InvokeRequired Then
Dim d As New SetTextCallback(AddressOf SetTitle)
Me.Invoke(d, New Object() {[text]})
Else
Me.Text = [text]
End If
End Sub
Sub thr1()
Dim linez As Integer = 1
Dim linex As Integer = 1
For Each line As String In System.IO.File.ReadAllLines("index.db")
linez += 1
Next
For Each line As String In System.IO.File.ReadAllLines("index.db")
Try
Application.DoEvents()
Dim a As saLoginResponse = JsonConvert.DeserializeObject(Of saLoginResponse)(line) ' source <> mine
Application.DoEvents()
MainList.Add(New EntryType(a.id, Split(a.tags, " ")))
linex += 1
SetTitle("Search (loading, " & linex & " of " & linez & ")")
Catch ex As Exception
End Try
Next
SetTitle("Search")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim searchTags() As String = TextBox1.Text.Split(" ")
Dim query = MainList.Where(Function(et) et.Tags.Any(Function(tag) searchTags.Contains(tag))).ToList
For Each et In query
ListBox1.Items.Add(et.Id)
Next
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) ' test
MsgBox(Mid(ListBox1.SelectedItem.ToString, 1, 6)) ' test
End Sub 'test, removeonrelease
End Class
Public Class EntryType
Public Property Id As Integer
Public Property Tags() As String
Public Sub New(ByVal _id As Integer, ByVal _tags() As String)
Me.Id = Id
Me.Tags = Tags
End Sub
Public Function GetTags() As String
'to tell the Listbox what to display
Return Tags
End Function
Public Function GetId() As Integer
'to tell the Listbox what to display
Return Id
End Function
End Class
I also edited your EntryType class; I added a constructor, removed toString and added GetTags and GetID.
Example "DB" im working with ("db" as "index.db" in exec dir):
{"tags":"vb.net lol test qwikscopeZ","id":123456}
{"tags":"vb.net lol test","id":12345}
{"tags":"vb.net lol","id":1234}
{"tags":"vb.net","id":123}
{"tags":"cpp","id":1}
{"tags":"cpp graphical","id":2}
{"tags":"cpp graphical fractals","id":3}
{"tags":"cpp graphical fractals m4th","id":500123}
Error:
Debugger:Exception Intercepted: _Lambda$__1, Form2.vb line 44
An exception was intercepted and the call stack unwound to the point before the call from user code where the exception occurred. "Unwind the call stack on unhandled exceptions" is selected in the debugger options.
Time: 13.11.2014 03:46:10
Thread:<No Name>[5856]
Here is a Lambda query. The Where filters on a predicate, since Tags is an Array you can use the Any function to perform a search based on another Array-SearchTags. You can store each class object in the Listbox since it stores Objects, you just need to tell it what to display(see below).
Public Class EntryType
Public Property Id As Integer
Public Property Tags() As As String
Public Overrides Function ToString() As String
'to tell the Listbox what to display
Return String.Format("{0} - {1}", Me.Id, String.Join(Me.Tags, " "))
End Function
End Class
Dim searchTags = textbox1.Text.Split(" "c)
Dim query = mainlist.Where(Function(et) et.Tags.Any(Function(tag) searchTags.Contains(tag))).ToList
For Each et In query
Listbox1.Items.Add(et)
Next

how to pick value and name for item in listbox in vb.net

i want to pick payrollcode when listbox is selected though list should appear as payrollname.Once I have the paycode i can then use it in another query.I have a php background so this is alittle tricky for me.
Dim cmd As New SqlCommand("select tblPayrollCode.payrollcode_name ,tblPayrollCode.payrollcode_code from tblPayrollCode where tblPayrollCode.systemcode_id=0 and tblPayrollCode.deduction= 'false'", Getconnect)
Dim dr As SqlDataReader
Getconnect()
dr = cmd.ExecuteReader
While dr.Read
lsttrans.Items.Add(dr.Item("payrollcode_name"), payrollcode_code)
End While
dr.Close()
Create a class to create objects that keep each display item/data pair. The class needs to specify an overriden ToString method. This method overrides the ToString method of the base class (Object) to ensure that your display item and not the class name is displayed in the list box.
Public Class CListItem
Private m_sItemData As String
Private m_sItemDisplay As String
Public Sub New(ByVal sValue As String, ByVal sData As String)
m_sItemData = sData
m_sItemDisplay = sValue
End Sub
Public Overrides Function ToString() As String
Return m_sItemDisplay
End Function
Public Property ItemData() As String
Get
Return m_sItemData
End Get
Set(ByVal Value As String)
m_sItemData = Value
End Set
End Property
Public Property ItemDisplay() As String
Get
Return m_sItemDisplay
End Get
Set(ByVal Value As String)
m_sItemDisplay = Value
End Set
End Property
End Class
Execute the loop like this. This adds a CListItem object to the list box's items collection and displays the first parameter that is passed to the constructor.
While dr.Read
lsttrans.Items.Add(New CListItem(dr.Item("payrollcode_name").ToString, dr.Item("payrollcode_code").ToString))
End While
You can then retrieve the payrollcode_name and payrollcode_code by adding this code and double clicking on the list box:
Private Sub lsttrans_DoubleClick(sender As Object, e As EventArgs) Handles lsttrans.DoubleClick
Dim sSelectedDisplay As String = DirectCast(lsttrans.SelectedItem, CListItem).ItemDisplay
Dim sSelectedData As String = DirectCast(lsttrans.SelectedItem, CListItem).ItemData()
MessageBox.Show("The selected payrollcode_name is " & sSelectedDisplay & " and the selected payrollcode_code is " & sSelectedData)
End Sub
Adding onto #Guru Josh's answer
While dr.Read
lsttrans.Items.Add(New CListItem(dr.Item("payrollcode_name"), dr.Item("payrollcode_code")))
End While
I changed the last bit to the above works fine now.
string col1Value = dr["ColumnOneName"].ToString()

Retrieve a object from a list of objects in visual basic and use it to fill text/combo boxes

I have a class as seen below:
Public Class parameters
Public Property test As String
Public Property test_type As String
Public Property user_test_name As String
Public Property meas As String
Public Property spec As String
...etc
End Class
I make a list of objects that I import from a csv somewhere. The user_test_name's from the list gets sent to a list box:
For Each parameters In param
' MsgBox(parameters.user_test_name)
ListBox1.Items.Add(parameters.user_test_name)
Next
now when the user selects something from the list i want the rest of the properties of that particular user_test_name object to populate in certain text/combo boxes in the application. Here is how I grab what is selected.
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
Dim selected_name As String = ListBox1.SelectedItem()
' MsgBox(selected_name)
find_object_by_user_test_name(selected_name)
End Sub
Now i'm having difficulty finding the object with the selected_name from the list and using its properties to fill the text.combo boxes. I tried the following to no success:
Public Sub find_object_by_user_test_name(ByVal description)
MsgBox(description)
Dim matches = From parameters In param
Where parameters.user_test_name = description
Select parameters
' MsgBox(matches)
' MsgBox(matches.user_test_name)
TextBox1.Text = matches.test
TextBox2.Text = matches.test_name
etc,,, on and on
' populate_area(matches)
End Sub
Instead of adding the name (a string) to the ListBox, add your actual INSTANCE to it.
First, override ToString() in your class so that it displays properly in your ListBox:
Public Class parameters
Public Property test As String
Public Property test_type As String
Public Property user_test_name As String
Public Property meas As String
Public Property spec As String
Public Overrides Function ToString() As String
Return user_test_name
End Function
End Class
Next, add each instance to the ListBox:
For Each parameters In param
ListBox1.Items.Add(parameters)
Next
Now, the SelectedIndexChanged() event, you can cast the SelectedItem() item back to parameters and you already have everything at your disposal:
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
If ListBox1.SelectedIndex <> -1 Then
Dim P As parameters = DirectCast(ListBox1.SelectedItem, parameters)
' ... do something with "P" ...
Debug.Print(P.user_test_name & " --> " & P.test)
End If
End Sub
If the user_test_names are unique, it may be easier to use a dictionary and retrieve the objects that way.
Dim params As New Dictionary(Of String, parameters)
params.add(MyParameterObject.user_test_name, MyParameterObject)
Then
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
Dim selected_name As String = ListBox1.SelectedItem()
Dim selected_param as parameters = params(selected_name)
End Sub
Something like this should do it:
Public Sub find_object_by_user_test_name(ByVal description As String)
' assuming param is your list of parameter objects
For Each p In param
If p.user_test_name = description Then
TextBox1.Text = p.test
TestBox2.Text = p.test_name
...
Exit For
End If
Next
End Sub
A few notes about your code. First, you can't allow two objects to have the same user_test_name. Second, you can't use parameters as a variable name if you already have a class called parameters in your current namespace (which you do).
There is a simpler solution than any of these--just do the following:
Dim i as Integer = ListBox1.SelectedIndex
Then you can use i as an index to your original list of objects.

How can I make a list in a Repeater Section?

I need to create a repeater section that will show 4 columns - First Name, Last Name, a link based off of stored column data that says.
All the data plus some extra not being used is in a players profile. How do I link the data on the code-behind to the repeater control with the databinders?
I am using visual studio 2008, VB.NET for the code behind.
Have you considered using a DataGrid instead of a repeater?
Here's a bit of a breakdown on when to use each.
http://msdn.microsoft.com/en-us/library/aa479015.aspx
To more directly answer your question you'll need to set the Repeater's DataSource property to a DataView or an ArrayList. As such:
Sub Page_Load(Sender As Object, e As EventArgs)
If Not IsPostBack Then
Dim values As New ArrayList()
values.Add(New PositionData("Microsoft", "Msft"))
values.Add(New PositionData("Intel", "Intc"))
values.Add(New PositionData("Dell", "Dell"))
Repeater1.DataSource = values
Repeater1.DataBind()
Repeater2.DataSource = values
Repeater2.DataBind()
End If
End Sub
Public Class PositionData
Private myName As String
Private myTicker As String
Public Sub New(newName As String, newTicker As String)
Me.myName = newName
Me.myTicker = newTicker
End Sub
Public ReadOnly Property Name() As String
Get
Return myName
End Get
End Property
Public ReadOnly Property Ticker() As String
Get
Return myTicker
End Get
End Property
End Class

how to add value to combobox item

How can I add data value of each item to combobox in Visual Basic 2010?
Like html drop-down box.
Or is there anyway to add values to each item ?
I am adding item from MySQL database like this:
Command = New MySqlCommand("SELECT * FROM `maillist` WHERE l_id = '" & id & "'", connection)
Command.CommandTimeout = 30
Reader = Command.ExecuteReader()
If Reader.HasRows = True Then
While Reader.Read()
ComboBox1.Items.Add(Reader("name"))
End While
End If
I need to add Reader("ID") as value of each item...
Although this question is 5 years old I have come across a nice solution.
Use the 'DictionaryEntry' object to pair keys and values.
Set the 'DisplayMember' and 'ValueMember' properties to:
Me.myComboBox.DisplayMember = "Key"
Me.myComboBox.ValueMember = "Value"
To add items to the ComboBox:
Me.myComboBox.Items.Add(New DictionaryEntry("Text to be displayed", 1))
To retreive items like this:
MsgBox(Me.myComboBox.SelectedItem.Key & " " & Me.myComboBox.SelectedItem.Value)
I am assuming that you are wanting to add items to a ComboBox on an Windows form. Although Klaus is on the right track I believe that the ListItem class is a member of the System.Web.UI.WebControls namespace. So you shouldn't be using it in a Windows forms solution. You can, however, create your own class that you can use in its place.
Create a simple class called MyListItem (or whatever name you choose) like this:
Public Class MyListItem
Private mText As String
Private mValue As String
Public Sub New(ByVal pText As String, ByVal pValue As String)
mText = pText
mValue = pValue
End Sub
Public ReadOnly Property Text() As String
Get
Return mText
End Get
End Property
Public ReadOnly Property Value() As String
Get
Return mValue
End Get
End Property
Public Overrides Function ToString() As String
Return mText
End Function
End Class
Now when you want to add the items to your ComboBox you can do it like this:
myComboBox.Items.Add(New MyListItem("Text to be displayed", "value of the item"))
Now when you want to retrieve the value of the selected item from your ComboBox you can do it like this:
Dim oItem As MyListItem = CType(myComboBox.SelectedItem, MyListItem)
MessageBox.Show("The Value of the Item selected is: " & oItem.Value)
One of the keys here is overriding the ToString method in the class. This is where the ComboBox gets the text that is displayed.
Matt made an excellent point, in his comment below, about using Generics to make this even more flexible. So I wondered what that would look like.
Here's the new and improved GenericListItem class:
Public Class GenericListItem(Of T)
Private mText As String
Private mValue As T
Public Sub New(ByVal pText As String, ByVal pValue As T)
mText = pText
mValue = pValue
End Sub
Public ReadOnly Property Text() As String
Get
Return mText
End Get
End Property
Public ReadOnly Property Value() As T
Get
Return mValue
End Get
End Property
Public Overrides Function ToString() As String
Return mText
End Function
End Class
And here is how you would now add Generic items to your ComboBox. In this case an Integer:
Me.myComboBox.Items.Add(New GenericListItem(Of Integer)("Text to be displayed", 1))
And now the retrieval of the item:
Dim oItem As GenericListItem(Of Integer) = CType(Me.myComboBox.SelectedItem, GenericListItem(Of Integer))
MessageBox.Show("The value of the Item selected is: " & oItem.Value.ToString())
Keep in mind that the type Integer can be any type of object or value type. If you want it to be an object from one of your own custom classes that's fine. Basically anything goes with this approach.
If you want to use SelectedValue then your combobox must be databound.
To set up the combobox:
ComboBox1.DataSource = GetMailItems()
ComboBox1.DisplayMember = "Name"
ComboBox1.ValueMember = "ID"
To get the data:
Function GetMailItems() As List(Of MailItem)
Dim mailItems = New List(Of MailItem)
Command = New MySqlCommand("SELECT * FROM `maillist` WHERE l_id = '" & id & "'", connection)
Command.CommandTimeout = 30
Reader = Command.ExecuteReader()
If Reader.HasRows = True Then
While Reader.Read()
mailItems.Add(New MailItem(Reader("ID"), Reader("name")))
End While
End If
Return mailItems
End Function
Public Class MailItem
Public Sub New(ByVal id As Integer, ByVal name As String)
mID = id
mName = name
End Sub
Private mID As Integer
Public Property ID() As Integer
Get
Return mID
End Get
Set(ByVal value As Integer)
mID = value
End Set
End Property
Private mName As String
Public Property Name() As String
Get
Return mName
End Get
Set(ByVal value As String)
mName = value
End Set
End Property
End Class
Instead of adding Reader("Name") you add a new ListItem. ListItem has a Text and a Value property that you can set.
Yeah, for most cases, you don't need to create a class with getters and setters. Just create a new Dictionary and bind it to the data source. Here's an example in VB using a for loop to set the DisplayMember and ValueMember of a combo box from a list:
Dim comboSource As New Dictionary(Of String, String)()
cboMenu.Items.Clear()
For I = 0 To SomeList.GetUpperBound(0)
comboSource.Add(SomeList(I).Prop1, SomeList(I).Prop2)
Next I
cboMenu.DataSource = New BindingSource(comboSource, Nothing)
cboMenu.DisplayMember = "Value"
cboMenu.ValueMember = "Key"
Then you can set up a data grid view's rows according to the value or whatever you need by calling a method on click:
Private Sub cboMenu_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboMenu.SelectionChangeCommitted
SetListGrid(cboManufMenu.SelectedValue)
End Sub
Now you can use insert method instead add
' Visual Basic
CheckedListBox1.Items.Insert(0, "Copenhagen")