How to return matching value in textbox? - vb.net

I have a combo box that is populated by a csv. In my csv, I have 3 columns, the first column is id #s.

Maybe you can try ValueMember.
This is an example :
public partial class Form1 : Form
{
List<Student> listStudents = new List<Student>();
public Form1()
{
InitializeComponent();
listStudents.Add(new Student(101, "name1", "male"));
listStudents.Add(new Student(102, "name2", "female"));
listStudents.Add(new Student(103, "name3", "female"));
listStudents.Add(new Student(104, "name4", "male"));
var maleStudentList = listStudents.Where(student => student.gender == "male").ToList();
comboBox1.DisplayMember = "name";
comboBox1.ValueMember = "id";
comboBox1.DataSource = maleStudentList;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
label1.Text = ((Student)comboBox1.SelectedItem).id.ToString();
}
}
class Student
{
public int id { get; set; }
public string name { get; set; }
public string gender { get; set; }
public Student(int id, String name, String gender)
{
this.id = id;
this.name = name;
this.gender = gender;
}
}
Source : https://social.msdn.microsoft.com/Forums/windowsmobile/en-US/1a978579-1938-44cd-aab3-d1964548a814/why-dont-comboboxs-item-have-a-tag-property?forum=csharpgeneral

What I would do is create a class to represent a row in the CSV file and have your properties represent the columns. The reason for this is because you could then convert the CSV file to a list of your class and then bind the ComboBox to the list.
When you bind your ComboBox you will set the DisplayMember to the Description and the ValueMember to the Id.
I'm not sure how you're reading the CSV file nor do I know the name of your second column, so I'm making some assumptions in my example, but it should plenty to go off of. Please keep in mind, that there are likely better ways of parsing CSV files, this is just an quick example to demonstrate how the binding would work.
This is how you'd define your class:
Public Class CsvRow
Public Property Id As Integer
Public Property Column2 As String
Public Property Description As String
End Class
This is how you'd read the CSV and bind the objects.
Dim lines() As String = IO.File.ReadAllLines("my-file.csv")
Dim rows As New List(Of CvsRow)()
For Each line In lines
Dim cells() As String = line.Split(","c)
Dim row As New CvsRow()
If (cells.Length = 3 AndAlso Integer.TryParse(cells(0).Trim(), row.Id) Then
row.Column2 = cells(1)
row.Description = cells(2)
rows.Add(row)
End If
Next
Dim binder As New BindingSource()
binder.DataSource = rows
ComboBoxDescription.DataSource = binder.DataSource
ComboBoxDescription.DisplayMember = "Description"
ComboBoxDescription.ValueMember = "Id"
Now in the ComboBox's SelectedValueChanged you can get the SelectedItem and convert it back to a CsvRow to get the properties:
Private Sub ComboBoxDescription_SelectedValueChanged(sender As Object, e As EventArgs) Handles ComboBoxDescription.SelectedValueChanged
If (ComboBoxDescription.SelectedItem IsNot Nothing) Then
Dim row As CvsRow = DirectCast(ComboBoxDescription.SelectedItem, CvsRow)
'row.Id and row.Description are now available
End If
End Sub

I made a class called Product with 3 properties. I guessed that the middle column would be the name of the product. When you add an object to a combo box, the combo will call .ToString on the object to get what to display. I provided an override of the .ToString method to tell the combo to display the name property of the Product object. Finally, I replaced the default constructor with a parameterized one to make creating the Product with all its properties easier.
In the FillCombo method (probably called from the Form.Load) I read your data file. You can change that to however you are reading the file. The important part is where you call the New method of the product adding each of the properties from your file. The entire Property object will all its properties are added to the combo box.
The SelectedIndexChanged event shows you how to retrieve the properties and display them wherever you want. To the combo box, it is an Object. You must cast it back to a Product to be able to access its properties.
Public Class Product
Public Property ID As Integer
Public Property Name As String
Public Property Description As String
Public Overrides Function ToString() As String
Return Name
End Function
Public Sub New(iID As Integer, sName As String, sDesc As String)
ID = iID
Name = sName
Description = sDesc
End Sub
End Class
Private Sub FillCombo()
Dim lines = File.ReadAllLines("data.csv")
For Each line In lines
Dim props = line.Split(","c)
Dim p As New Product(CInt(props(0)), props(1), props(2))
ComboBox1.Items.Add(p)
Next
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim p = DirectCast(ComboBox1.SelectedItem, Product)
TextBox1.Text = p.ID.ToString
TextBox2.Text = p.Description
End Sub

Related

VB.NET Search ListBox for string and return specific data

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

How can store a datagridview as a array in a cell of a mysql table

I want to store the content of a DataGridView in a array
and the other way round I want to read a array into a Datagridview.
I found this class on the net
Public Class Loads
Private L_nr As String
Private L_plz As String
Private L_km As String
Public Sub New(ByVal nr, ByVal plz, ByVal km)
L_nr = nr
L_plz = plz
L_km = km
End Sub
Public Property nr() As String
Get
Return L_nr
End Get
Set(ByVal Value As String)
L_nr = Value
End Set
End Property
Public Property plz() As String
Get
Return L_plz
End Get
Set(ByVal Value As String)
L_plz = Value
End Set
End Property
Public Property km() As String
Get
Return L_km
End Get
Set(ByVal Value As String)
L_km = Value
End Set
End Property
End Class
I xan use it like this
Private Sub DataGridViewLoads1_Click(sender As Object, e As EventArgs) Handles DataGridViewLoads1.Click
Dim al As New Collections.ArrayList()
al.Add(New Loads(123, 234, 1971))
DataGridViewLoads1.DataSource = al
End Sub
But its not what I want
You can use collection of class instances for displaying and editing data in DataGridView
Public Class Person
Public Property Id As Integer
Public Property Name As String
End Class
Create collection and show it in DataGridView
Dim persons = new List(Of Person) From
{
New Person { .Id = 1, .Name = "One" },
New Person { .Id = 2, .Name = "Two" },
New Person { .Id = 3, .Name = "Three" }
}
yourDataGridView.DataSource = persons
When you want save all data from DataGridView use same instance of persons or cast it from .DataSource
Dim dataToSave = DirectCast(yourDataGridView.DataSource, List(Of Person))
Then serialize data to string in json format for example(feel free to use any other format)
Dim serializedData AS String = Newtonsoft.Json.JsonConvert.SerializeObject(dataToSave)
Then save that string in database.
For displaying data from database:
// retrieve value from database
Dim serializedData As String = GetFromDatabaseYourFunction()
Dim data = Newtonsoft.Json.JsonConvert.DeserializeObject(Of List(Of Person))(serializedData)
yourDataGridView.DataSource = data

Using Delegates in vb.net

I'm new to vb.net and trying to build a win CE app in vb.net. The sdk of the handheld device is in C# which I converted with an online converter to vb.net.
Below is the C# code:
public class DecodeEventArgs : EventArgs
{
private string barcode;
private byte type;
public DecodeEventArgs(string barcodeData, byte typeData)
{
barcode = barcodeData;
type = typeData;
}
public string Barcode
{
get { return barcode; }
set { barcode = value; }
}
public byte Type
{
get { return type; }
set { type = value; }
}
}
Converted to vb.net as:
Public Class DecodeEventArgs
Inherits EventArgs
Public barcode As String
Public type As Byte
Public Sub New(ByVal barcodeData As String, ByVal typeData As Byte)
barcode = barcodeData
type = typeData
End Sub
Public Property pBarcode() As String
Get
Return barcode
End Get
Set(ByVal value As String)
barcode = value
End Set
End Property
Public Property pType() As Byte
Get
Return type
End Get
Set(ByVal value As Byte)
type = value
End Set
End Property
End Class
In my conversion from C# I added a 'p' to the name of the Properties as you see in my vb.net code because I had a error that said
Barcode is already declared as a public string in this class
I'm not sure if that is part of my problem but my real issue is, on a form they used .BeginInvoke to call the class with this code:
void scanner_DecodeEvent(object sender, DecodeEventArgs e)
{
Win32.sndPlaySound(Properties.Resources.Scan, Win32.SND_ASYNC | Win32.SND_MEMORY);
this.BeginInvoke((Action<string>)delegate(string barcode)
{
scanCount = 0;
ListViewItem item = new ListViewItem(new string[] { barcode });
lstView.Items.Insert(0, item);
}, e.Barcode);
}
Which I converted to vb.net as:
Private Sub scanner_DecodeEvent(ByVal sender As Object, ByVal e As DecodeEventArgs)
PlaySound()
Me.BeginInvoke(DirectCast(Barcode As String) )
scanCount = 0
Dim item As New ListViewItem(New String() {barcode})
lstView.Items.Insert(0, item)
End Sub
Which gives me an error about Barcode not being declared. This is where I'm stuck. Thanks for your assistance in advance
That C# snippet creates an anonymous method which it invokes to perform the actions on the UI thread, and it sends e.Barcode as a parameter. Your VB.NET conversion only tries to invoke some strange, and incomplete, use of DirectCast. DirectCast is not needed in the VB.NET conversion as you don't have any delegate keyword which you must cast to a delegate method.
Your most simple solution would be to use a Lambda method:
Me.BeginInvoke(Sub() 'Lambda anonymous method.
scanCount = 0
Dim item As New ListViewItem(New String() {e.Barcode})
lstView.Items.Insert(0, item)
End Sub)
EDIT:
Since you get errors when using the lambda expression I assume you target .NET Framework 3.5 or lower. For that matter it gets a bit more complicated as you must now put the code in a different method:
Private Sub AddBarcode(ByVal Barcode As String)
scanCount = 0
Dim item As New ListViewItem(New String() {Barcode})
lstView.Items.Insert(0, item)
End Sub
Then you must declare your own delegate method which you can use to perform the invocation:
Delegate Sub AddBarcodeDelegate(ByVal Barcode As String)
Private Sub scanner_DecodeEvent(ByVal sender As Object, ByVal e As DecodeEventArgs)
Me.BeginInvoke(New AddBarcodeDelegate(AddressOf AddBarcode), e.Barcode)
End Sub

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")