How to remove an item in a two dimensional array with a list box - vb.net

Hi I have an assignment for coding and I am having a hard time to figure out how to code it. My teacher wanted us to build a program that uses a list box that holds product names and a 2-D array that holds quantity in stock and price. Then in the one of the buttons in the application, which is the remove button, the item in the list box as well as the data from the array should be removed. When the user deletes an item, not only must the list loose the name of the item but the 2-D array must also be readjusted.

I am sorry. My brain just doesn't want to do what your teacher wants. If you can make sense of the following, maybe you can convince your teacher not to ask you to use 2D arrays in this instance.
Public Class Product
'These are automatic properties
'The compiler provides the getter, setter and backer fields.
Public Property Name As String
Public Property Quantiy As Integer
Public Property Price As Double
'ToString is a method inherited from Object. It will return a fully
'qualified name of the Type, not what we want in a ListBox
'The ListBox will call .ToString on Product and we will get the Name
'property of the Product object.
Public Overrides Function ToString() As String
Return Name
End Function
Public Sub New(prodName As String, prodQuantity As Integer, prodPrice As Double)
'We add a parameterized Constructor to make it easy to add our Product objects
'to the ListBox. Intelisense will help out once we type the New keyword
Name = prodName
Quantiy = prodQuantity
Price = prodPrice
End Sub
End Class
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'The New keyword calls the Constructor of the Product class
'so a Product object is added to the ListBox
ListBox1.Items.Add(New Product("Bell", 30, 2.98))
ListBox1.Items.Add(New Product("Book", 7, 200))
ListBox1.Items.Add(New Product("Candle", 42, 14.99))
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
'When a Product is deleted from the ListBoX with the RemoveItem button
'this event will fire. (The index changed) -1 means nothing is selected which is
'what happens after the delete. If Nothing is selected our cast will fail and
'we will get an exception.
If ListBox1.SelectedIndex <> -1 Then
'The ListBox items are objects but underneath the objects are Products
'so we can Cast the object back to a Product
Dim p As Product = CType(ListBox1.SelectedItem, Product)
'All the properties of the Procuct are then available
MessageBox.Show($"Product Name is {p.Name}. There are {p.Quantiy} on hand. The price is {p.Price:N2}")
End If
End Sub
Private Sub btnRemoveItem_Click(sender As Object, e As EventArgs) Handles btnRemoveItem.Click
ListBox1.Items.Remove(ListBox1.SelectedItem)
End Sub
End Class

This should work, though it's really the wrong way to approach this:
LBProducts = Form ListBox
lblQuantity = Form Label
lblPrice = Form Label
btnDelete = Form Button
Public Class Form1
'5 Rows, (Price, Qty)
Private ProductArray(5, 1) As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
LBProducts.Items.Add("Apples")
LBProducts.Items.Add("Bananas")
LBProducts.Items.Add("Grapes")
LBProducts.Items.Add("Oranges")
LBProducts.Items.Add("Peaches")
For x = 0 To 5
ProductArray(x, 0) = x
ProductArray(x, 1) = 1
Next
End Sub
Private Sub LBProducts_SelectedIndexChanged(sender As Object, e As EventArgs) Handles LBProducts.SelectedIndexChanged
Dim Index = LBProducts.SelectedIndex()
If Index >= 0 Then
lblPrice.Text = "Price: " & ProductArray(Index, 0)
lblQuantity.Text = "Qty: " & ProductArray(Index, 1)
End If
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Dim Index = LBProducts.SelectedIndex()
If Index >= 0 Then
LBProducts.Items.RemoveAt(Index)
Dim NewArray(UBound(ProductArray) - 1, 1) As Integer
Dim i As Integer = 0
For x = 0 To UBound(ProductArray)
If x <> Index Then
NewArray(i, 0) = ProductArray(x, 0)
NewArray(i, 1) = ProductArray(x, 1)
i += 1
End If
Next
ProductArray = NewArray
End If
End Sub
End Class

Related

Sort items in a listbox which contain integer from highest to lowest for VB.NET

(I have about 3 weeks of knowledge so sorry if I can't use the right naming conventions (like string for words)).
I would recommend reading this and then looking at the image I've provided. Also anything red ignore it and blue shows where data travels
To sum it up, I'm entering data, for example, a most football goals challenge and will enter the persons name how many points they achieved (1-100) and the event (series 1,2 or 3) this will then be entered into the 'solo' listbox and repeated until 20 participants have been added into the listbox. Then I will click the 'Add to Rank' button and all the items within solo listbox will be added to the 'RANK', listbox.
Now this is the tricky part, all I'm trying to do is sort the listbox by descending points (most to least, 100-1) which is why I put the points first, but I don't know how to use classes or arrays.
Can you maybe share you code? would be nice too see what you are doing.
Dim List As New List(Of Integer)
'Add ListBox Items to List
For Each ListBoxItem In ListBox1.Items
List.Add(ListBoxItem)
Next
'Sort the List and Clear the ListBox
List.Sort()
ListBox1.Items.Clear()
'Add to ListBox Ascending
For Each ListItem In List
ListBox1.Items.Add(ListItem)
Next
'Add to ListBox Descending
For i = List.Count - 1 To 0 Step -1
ListBox1.Items.Add(List(i))
Next
small example here for you
Don't store the data in the UI. Store it in data structures in code. Here is some code you can use to do that.
First of all, make a class to hold a Solo. This is a fundamental of object oriented programming. It will give you easy access to the properties of the solo, importantly the score which you can use to sort. Then it doesn't matter in what order you display it.
Public Class Solo
Public Sub New(name As String, score As Integer, series As String)
Me.Name = name
Me.Score = score
Me.Series = series
End Sub
Public Property Name As String
Public Property Score As Integer
Public Property Series As String
Public ReadOnly Property Text As String
Get
Return $"{Name}, {Series}, {Score} Points"
End Get
End Property
End Class
In your form, you can use this code. It will bind the data to the ListBoxes. You still have the data in your code to do other things with.
Private serieses As List(Of String)
Private solos As List(Of Solo)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
serieses = New List(Of String)() From {"Series 1", "Series 2", "Series 3"}
solos = New List(Of Solo)()
Me.SeriesComboBox.DataSource = serieses
End Sub
Private Sub AddButton_Click(sender As Object, e As EventArgs) Handles AddButton.Click
Dim score As Integer
If Not String.IsNullOrEmpty(NameTextBox.Text) AndAlso Integer.TryParse(ScoreTextBox.Text, score) Then
solos.Add(New Solo(NameTextBox.Text, score, SeriesComboBox.Text))
bindSolos()
End If
End Sub
Private Sub ShowRankButton_Click(sender As Object, e As EventArgs) Handles ShowRankButton.Click
bindRanks()
End Sub
Private Sub bindSolos()
SoloListBox.DataSource = Nothing
SoloListBox.DataSource = solos
SoloListBox.DisplayMember = "Text"
End Sub
Private Sub bindRanks()
RankListBox.DataSource = Nothing
RankListBox.DataSource = solos.OrderByDescending(Function(s) s.Score).ToList()
RankListBox.DisplayMember = "Text"
End Sub
Note the series are populated in Form_Load, not in the designer. In fact there is no data in the designer, as it should be.
You can rethink the rank button. You don't need it at all and can just bind the sorted ranks when you add, like this
Private Sub bindSolos()
SoloListBox.DataSource = Nothing
SoloListBox.DataSource = solos
SoloListBox.DisplayMember = "Text"
RankListBox.DataSource = solos.OrderByDescending(Function(s) s.Score).ToList()
RankListBox.DisplayMember = "Text"
End Sub
And really, you can just automatically just sort the solo ListBox and get rid of the second ListBox, so when you Add, they are always displayed in the solo ListBox sorted.
Private Sub bindSolos()
SoloListBox.DataSource = Nothing
SoloListBox.DataSource = solos.OrderByDescending(Function(s) s.Score).ToList()
SoloListBox.DisplayMember = "Text"
End Sub

VB.Net populating text boxes from text file

I'm creating an inventory management system where the data is stored in a text file. I'm able to save data to the text file, however on the tracker screen it should show current inventory such as: Manufacturer, Processor, Video, Form, RAM, etc. However, all my text boxes remain blank and I'm not sure why. It's not reading properly or updating the text.
frmTracker.vb
Private Sub txtManufacturer_TextChanged(sender As Object, e As EventArgs) Handles txtManufacturer.TextChanged
Dim objMyStreamReader = System.IO.File.OpenText("inventory.txt")
Dim strInventory = objMyStreamReader.ReadLine()
objMyStreamReader.Close()
txtManufacturer.AppendText(strInventory)
End Sub
This is how I'm currently saving the data to the text file.
frmItemEntry.vb
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim objMyStreamReader As System.IO.StreamReader
Dim objMyStreamWriter As System.IO.StreamWriter = System.IO.File.CreateText("inventory.txt")
Dim strInventory As String
objMyStreamWriter.WriteLine(txtManufacturerEntry.Text)
objMyStreamWriter.WriteLine(txtProcessorEntry.Text)
objMyStreamWriter.WriteLine(txtVideoEntry.Text)
objMyStreamWriter.WriteLine(txtFormEntry.Text)
objMyStreamWriter.WriteLine(txtRamEntry.Text)
objMyStreamWriter.WriteLine(txtVramEntry.Text)
objMyStreamWriter.WriteLine(txtHdEntry.Text)
objMyStreamWriter.WriteLine(chkWirelessEntry.CheckState)
objMyStreamWriter.Close()
Me.Close()
End Sub
Example from inventory.txt
Dell
i5
Nvidia
Desktop
8
4
600
0
To be honest, controls should never be used as the primary store for your data in a program. You should really be creating a class and a list of that class to store your data.
You can then read your data into the list from your file, and then, display it from there in your form.
There are several ways of navigating through the data and saving updates. The suggestion below uses buttons for next item and previous item, and a button to save update the file.
It's all pretty self explanatory, but if there's something your not sure about, please have a google and learn something new :-D
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ReadDataFile()
DisplayItem(0)
End Sub
Private Class InventoryItem
Public Property Manufacturer As String
Public Property Processor As String
Public Property Video As String
Public Property FormFactor As String
Public Property Ram As String
Public Property VRam As String
Public Property Hd As String
Public Property Wireless As CheckState
Public Sub New()
Manufacturer = ""
Processor = ""
Video = ""
FormFactor = ""
Ram = ""
VRam = ""
Hd = ""
Wireless = CheckState.Unchecked
End Sub
End Class
Dim Inventory As New List(Of InventoryItem)
Dim currentItemIndex As Integer
Private Sub ReadDataFile()
Using objMyStreamReader As New StreamReader("k:\inventory.txt")
Do Until objMyStreamReader.EndOfStream
Dim newItem As New InventoryItem
newItem.Manufacturer = objMyStreamReader.ReadLine()
newItem.Processor = objMyStreamReader.ReadLine()
newItem.Video = objMyStreamReader.ReadLine()
newItem.FormFactor = objMyStreamReader.ReadLine()
newItem.Ram = objMyStreamReader.ReadLine()
newItem.VRam = objMyStreamReader.ReadLine()
newItem.Hd = objMyStreamReader.ReadLine()
Dim wirelessValue As String = objMyStreamReader.ReadLine()
If wirelessValue = "0" Then
newItem.Wireless = CheckState.Unchecked
ElseIf wirelessValue = "1" Then
newItem.Wireless = CheckState.Checked
End If
Inventory.Add(newItem)
Loop
End Using
End Sub
Private Sub SaveDataFile()
Using objMyStreamWriter As New System.IO.StreamWriter("k:\inventory.txt", False)
For Each item As InventoryItem In Inventory
objMyStreamWriter.WriteLine(item.Manufacturer)
objMyStreamWriter.WriteLine(item.Processor)
objMyStreamWriter.WriteLine(item.Video)
objMyStreamWriter.WriteLine(item.FormFactor)
objMyStreamWriter.WriteLine(item.Ram)
objMyStreamWriter.WriteLine(item.VRam)
objMyStreamWriter.WriteLine(item.Hd)
If item.Wireless = CheckState.Checked Then
objMyStreamWriter.WriteLine("1")
Else
objMyStreamWriter.WriteLine(0)
End If
Next
End Using
End Sub
Private Sub DisplayItem(index As Integer)
With Inventory(index)
txtManufacturerEntry.Text = .Manufacturer
txtProcessorEntry.Text = .Processor
txtVideoEntry.Text = .Video
txtFormEntry.Text = .FormFactor
txtRamEntry.Text = .Ram
txtVramEntry.Text = .VRam
txtHdEntry.Text = .Hd
chkWirelessEntry.CheckState = .Wireless
End With
End Sub
Private Sub BtnUpdateItem_Click(sender As Object, e As EventArgs) Handles BtnUpdateItem.Click
With Inventory(currentItemIndex)
.Manufacturer = txtManufacturerEntry.Text
.Processor = txtProcessorEntry.Text
.Video = txtVideoEntry.Text
.FormFactor = txtFormEntry.Text
.Ram = txtRamEntry.Text
.VRam = txtVramEntry.Text
.Hd = txtHdEntry.Text
.Wireless = chkWirelessEntry.CheckState
End With
SaveDataFile()
End Sub
Private Sub BtnPreviousItem_Click(sender As Object, e As EventArgs) Handles BtnPreviousItem.Click
If currentItemIndex > 0 Then
currentItemIndex -= 1
DisplayItem(currentItemIndex)
End If
End Sub
Private Sub BtnNextItem_Click(sender As Object, e As EventArgs) Handles BtnNextItem.Click
If currentItemIndex < Inventory.Count - 1 Then
currentItemIndex -= 1
DisplayItem(currentItemIndex)
End If
End Sub
First change the format of your text file.
Dell,i5,Nvidia,Desktop,8,2,600,True
Acer,i7,Intel,Desktop,16,4,1GB,True
HP,Pentium,Diamond Viper,Desktop,4,2,200,False
Surface Pro,i7,Intel,Laptop,8,2,500,True
Each line is a record and each field in the record is separated by a comma (no spaces so we don't have to .Trim in code) (a space within a field is fine, notice Surface Pro).
Now it is easier to read the file in code.
This solution uses a BindingSource and DataBindings. This simplifies Navigation and editing and saving the data.
Public Class Form5
Private bs As BindingSource
Private dt As New DataTable
#Region "Set Up the Form"
Private Sub Form5_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AddColumnsToDataTable()
FillDataTable()
AddDataBindings()
End Sub
Private Sub AddColumnsToDataTable()
'Prepare the DataTable to hold data
dt.Columns.Add("Manufacturer", GetType(String))
dt.Columns.Add("Processor", GetType(String))
dt.Columns.Add("Video", GetType(String))
dt.Columns.Add("Form", GetType(String))
dt.Columns.Add("RAM", GetType(String))
dt.Columns.Add("VRAM", GetType(String))
dt.Columns.Add("HD", GetType(String))
dt.Columns.Add("Wireless", GetType(Boolean))
End Sub
Private Sub FillDataTable()
'ReadAllLines returns an array of the lines in a text file
'inventory.txt is stored in the bin\Debug folder of your project
'This is the current directory so it does not require a full path.
Dim lines = File.ReadAllLines("inventory.txt")
'Now it is easy to split each line into fields by using the comma
For Each line As String In lines
'Split returns an array of strings with the value of each field
Dim items = line.Split(","c)
'Each item in the array can be added as a field to the DataTable row
dt.Rows.Add(items(0), items(1), items(2), items(3), items(4), items(5), items(6), CBool(items(7)))
'Notice that the last element is changed from a string to a boolean. This is
'the Wireless field which is bound to the check box. The string "True" or "False" is
'changed to a Boolean so it can be used as the .Checked property (see bindings)
Next
End Sub
Private Sub AddDataBindings()
'Create a new instance of the BindingSource class
bs = New BindingSource()
'Set the DataSource to the DataTable we just filled
bs.DataSource = dt
'Now you can set the bindings of each control
'The .Add method takes (Name of Property to Bind, the BindingSource to use, The Field name
'from the DataTable.
txtForm.DataBindings.Add("Text", bs, "Form")
txtHd.DataBindings.Add("Text", bs, "HD")
txtManufacturer.DataBindings.Add("Text", bs, "Manufacturer")
txtProcessor.DataBindings.Add("Text", bs, "Processor")
txtRam.DataBindings.Add("Text", bs, "RAM")
txtVideo.DataBindings.Add("Text", bs, "Video")
txtVram.DataBindings.Add("Text", bs, "VRAM")
'Notice on the CheckBox we are using the Checked property.
chkWireless.DataBindings.Add("Checked", bs, "Wireless")
End Sub
#End Region
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
'Add a blank row to the DataTable
'A Boolean is like a number, a String can be Nothing but a Boolean must
'have a value so we pass in False.
dt.Rows.Add(Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, False)
'Find the position of the last row
Dim i As Integer = bs.Count - 1
'Move to the new empty row
bs.Position = i
End Sub
#Region "Navigation Code"
Private Sub btnPrevious_Click(sender As Object, e As EventArgs) Handles btnPrevious.Click
'The binding source Position determins where in the data you are
'It starts at zero
If bs.Position = 0 Then
MessageBox.Show("This is the first item.")
Return 'This exits the sub, you can use Exit Sub in vb
'but Return is common in other languages so it is good to learn
Else
'As the position of the BindingSource changes the boud TextBoxes
'change their data.
bs.Position = bs.Position - 1
End If
End Sub
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
' If you are not at the end of the list, move to the next item
' in the BindingSource.
If bs.Position + 1 < bs.Count Then
bs.MoveNext()
' Otherwise, move back to the first item.
Else
bs.MoveFirst()
End If
End Sub
#End Region
#Region "Save the Data"
Private Sub SaveDataTable()
'Resave the whole file if this was a real app you would use a database
Dim sb As New StringBuilder
'A string builder keeps the code from creating lots of new strings
'Strings are immutable (can't be changed) so every time you think you are
'changing a string, you are actually creating a new one.
'The string builder is mutable (changable)
For Each row As DataRow In dt.Rows
'The ItemsArray returns an array of objects containing all the
'values in each column of the data table.
Dim rowValues = row.ItemArray
'This is a bit of Linq magic that turns the values (objects) into strings
'Underneath it is performing a For loop on each object in the array
Dim strRowValues = From o In rowValues
Select Convert.ToString(o)
'Now that we have strings we can use the String.Join with the comma
'to get the format of the text file
sb.AppendLine(String.Join(",", strRowValues))
Next
'Finally we change the StringBuilder to a real String
'The inventory.txt is stored in the bin\Debug directory so it is current directory
'no additional path required
File.WriteAllText("inventory.txt", sb.ToString)
End Sub
Private Sub Form5_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
'Because our binding is two-way any additions or changes to the text
'in the text boxes or check box are reflected in the DataTable.
SaveDataTable()
End Sub
#End Region
End Class
Once you remove the comments, there is really very little code here. The #Region...#End Region tags make it easy to collapse code sections you are not working on and find areas quickly.

Combo Box Returning -1 For SelectedIndex

I'm trying to pick up a combo box's selected index. This was working absolutely fine, then all of a sudden it started returning -1 no matter what item is selected
My code is:
Form Code
Private Sub Man_SelectedIndexChanged_1(sender As Object, e As EventArgs) Handles Man.SelectedIndexChanged, Units.SelectedIndexChanged
'Set Transducer Type
Call References.LevListAdd()
End Sub
References Module LevListAdd Sub
Public Sub LevListAdd()
Form1.Lev.Items.Clear()
If Form1.Man.Text = "Pulsar" Then
With Form1.Lev.Items
.Add("Ultra Range")
.Add("IMP Range")
.Add("Twin Range")
End With
End If
End Sub
This fills the combo box lev fine when the Man combo box item "Pulsar" is selected. I then want my users to click a button to generate some labels and stuff. The code is as such:
Button Click Code
Private Sub Generate_Click(sender As Object, e As EventArgs) Handles Generate.Click
If CheckGenerate() = False Then Exit Sub
Dim X = CheckGenerationType(Man.SelectedIndex, Lev.SelectedIndex, Level.Checked, Volume.Checked, ListBox1.SelectedIndex,
Units.SelectedIndex)
Call ParamPage(X)
End Sub
CheckGenerate simply checks that all boxes have been filled in. I pass the informtion from the form to the following function:
Public Function CheckGenerationType(Man As Integer, Lev As Integer, Level As Boolean, Volume As Boolean, TankType As Integer,
MeasurementUnit As Integer) As String
Dim M As Integer
Dim L As Integer
Dim CT As Integer
Dim TT As Integer
Dim Ms As Integer
M = Man
L = Lev
TT = TankType
Ms = MeasurementUnit
If Level = True Then
CT = 0
ElseIf Volume = True Then
CT = 1
End If
CheckGenerationType = CStr(M) + "." + CStr(L) + "." + CStr(CT) + "." + CStr(TT) + "." + CStr(Ms)
End Function
When the lev.selectedindex parameter arrives at this function, it reads -1. Even if the user has selected any of the 3 items. Can anyone explain why this is happening?
I've just tried your code. I get the same result (-1 in lev.SelectedIndex) and this was because jumped using tab through the controls my when i'm hitting the Man or Units Combobox it runs the LevListAdd() and then clears the Lev-ComboBox because of Form1.Lev.Items.Clear().
You should think about your call Man_SelectedIndexChanged_1 or maybe just use something like this:
Public Sub LevListAdd()
If Form1.Man.Text = "Pulsar" Then
Form1.Lev.Items.Clear()
instead of
Public Sub LevListAdd()
Form1.Lev.Items.Clear()
If Form1.Man.Text = "Pulsar" Then
And you should separate the calls from the man and unit ComboBoxes.
Private Sub Unit_SelectedIndexChanged_1(sender As Object, e As EventArgs) Handles Units.SelectedIndexChanged
' Do something
End Sub
Private Sub Man_SelectedIndexChanged_1(sender As Object, e As EventArgs) Handles Man.SelectedIndexChanged
Form1.Lev.Items.Clear()
Select Case Form1.Man.Text
Case "Pulsar"
With Form1.Lev.Items
.Add("Ultra Range")
.Add("IMP Range")
.Add("Twin Range")
End With
Case "animals"
With Form1.Lev.Items
.Add("dogs")
.Add("cats")
.Add("birds")
End With
End Select
End Sub

Dynamically add Items to Combobox VB.NET

I have 2 combobox in windows application. I want to programmatically add Items to second combobox based on what is selected in the first combobox.
This is what I do in the selected index change of the combobox:
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
Try
If ComboBox1.SelectedIndex = 0 Then
ComboBox2.Items.Add("MM")
ComboBox2.Items.Add("PP")
ElseIf ComboBox1.SelectedIndex = 1 Then
ComboBox2.Items.Add("SMS")
ElseIf ComboBox1.SelectedIndex = 2 Then
ComboBox2.Items.Add("MMS")
ComboBox2.Items.Add("SSSS")
End If
Catch ex As Exception
End Try
End Sub
It works fine, however, if I keep selecting different items it's keep adding the value over and over. I would like to add those values only once.
Also, when I add an item I would prefer to add an ID with the item description. I tried:
ComboBox2.Items.Add("SSSS", "1")
It seems that it's not working.
Any suggestions?
try this
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ComboBox1.SelectedIndexChanged
Try
If ComboBox1.SelectedIndex = 0 Then
If Not (ComboBox2.Items.Contains("MM")) And Not (ComboBox2.Items.Contains("PP")) Then
ComboBox2.Items.Add("MM")
ComboBox2.Items.Add("PP")
End If
ElseIf ComboBox1.SelectedIndex = 1 Then
If Not (ComboBox2.Items.Contains("SMS")) Then
ComboBox2.Items.Add("SMS")
End If
ElseIf ComboBox1.SelectedIndex = 2 Then
If Not (ComboBox2.Items.Contains("MMS")) And Not (ComboBox2.Items.Contains("SSSS")) Then
ComboBox2.Items.Add("MMS")
ComboBox2.Items.Add("SSSS")
End If
End If
Catch ex As Exception
End Try
Regarding:
"Also, when I add an item I would prefer to add an ID with the item
description"
You can use the AddRange function of the ComboBox or make a list as I show here and use it as a datasource - as #Plutonix mentioned in his comment.
With it you can add an array of objects of a type that holds a value and a description, given that you override the ToString base function (of Object class).
Here is such a class:
Public Class CodeAndDescription
Public code As String
Public description As String
Public Overrides Function ToString() As String
Return Me.code + " - " + description
End Function
End Class
Now make a list of that upper class and add it to the combobox. Something like:
Dim lstItems As List(Of CodeAndDescription) = GetList()
yourComboBox.Items.Clear()
yourComboBox.Items.AddRange(lstItems.ToArray)
Don't forget to Cast the retrieved object when you take it out of the combo:
Dim codeDesc As CodeAndDescription = TryCast(yourComboBox.Items(0), CodeAndDescription)
I've done this on a check list, but I think the principle is the same for a ComboBox.

VB.net Windows form (Working with Access Database) displaying a selected combobox item in a textbox

Hello All this is somewhat urgent as this assignment is due Sunday 11/12 at midnight
I have attached what I need help with it is selecting a combobox item then getting the data to display in the textboxes below
I really don't know how to approach it I double clicked the combobox and this is what I started with to try to just get the ID to display. I haven't attempted anything else. I commented out what I tried because it didn't work.
Public Class AppointmentsForm
Private aAppointments As New Appointments
'Instance of customers
Private aCustomers As New Customers
Private Sub AppointmentsForm_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
'Combobox must always have a DataSource, Display Member, and Value Member
'Load the ComboBox with customer name
cboCustomer.DataSource = aCustomers.Items
cboCustomer.DisplayMember = "CustName"
cboCustomer.ValueMember = "CustId"
cboCustomer.SelectedIndex = -1 'no items selected
' load the datagridview
ApptDataGridView.DataSource = aAppointments.Items
'do not show TypeID
ApptDataGridView.Columns(1).Visible = False
'.Columns(1) TypeID has index of 1 as it is Column 2 in the data sources
End Sub
Private Sub btnDelete_Click(sender As System.Object, e As System.EventArgs) Handles btnDelete.Click
'make sure that a record is selected first
If ApptDataGridView.SelectedRows.Count > 0 Then
Dim apptid As Integer
apptid = ApptDataGridView.SelectedRows(0).Cells(0).Value
'Delete selected record by calling the delte function
aAppointments.Delete(apptid)
End If
End Sub
Private Sub btnEdit_Click(sender As System.Object, e As System.EventArgs) Handles btnEdit.Click
'make sure row is selected get that row from the table ..... need to find by ID
'This is a query which you will create in the class
'Transfer information from that row to the form, display the form
If ApptDataGridView.SelectedRows.Count > 0 Then
modAppointmentsForm.ApptID = ApptDataGridView.SelectedRows(0).Cells(0).Value
modAppointmentsForm.ShowDialog()
End If
End Sub
End Class
HERE IS THE CLASS FOR APPOINTMENTS:
Public Class Appointments
Public adapter As New CompanyDataSetTableAdapters.SalesStaffTableAdapter
'error variable
Public Shared Property LastError As String
Public ReadOnly Property Items() As DataTable
Get
Dim table As DataTable = adapter.GetData
'sorted by Appointment id
table.DefaultView.Sort = "ID"
Return table
End Get
End Property
'create a function to combine date and time
Public Shared Function CombinedDateTime(aDate As DateTime, aTime As DateTime) As DateTime
'declare timespan variable
Dim tsDate As New TimeSpan(aTime.Hour, aTime.Minute, 0)
Return aDate.Add(tsDate)
End Function
HERE IS THE CLASS FOR CUSTOMERS:
Public Class Customers
'create a object variable (tableadapter)
'this will be used to creat instances of this class in the form
Private adapter As New CompanyDataSetTableAdapters.SalesStaffTableAdapter
'property to return a table using the GetData method
Public ReadOnly Property Items() As DataTable
Get
Dim table As DataTable = adapter.GetData
table.DefaultView.Sort = "First_Name"
Return table
End Get
End Property
'create a function to filter the customers by custid
Public Function GetByCustomerId(custid As Short) As DataTable
Dim table As DataTable = adapter.GetData 'entire table
'filter to get desired row(s)
table.DefaultView.RowFilter = " ID = " & custid
Return table
End Function
End Class
HERE IS THE CODE FOR THE FORM WITH THE COMBOBOX AND THE TEXTBOX'S SUCH AS ID, LASTNAME, FIRSTNAME, ETC. THAT NEED TO HAVE THE DATA DISPLAYED WHEN THE COMBOBOX ITEM IS SELECTED. AGAIN THE ID IS DISPLAYING WHEN I WRITE: IDTextBox.Text = SalesStaffComboBox.SelectedValue.ToString
BUT IF I DO THE SAME FOR THE OTHER TEXT BOXES (LastName.Text = SalesStaffComboBox.SelectedValue.ToString _____ FirstName.Text = SalesStaffComboBox.SelectedValue.ToString ) THE ID NUMBER IS DISPLAYED IN THEM AS WELL.
Public Class frmUpdateSalary
'instances of the required classes
Private aCustomers As New Customers
Private aAppointments As New Appointments
Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
Me.Close()
End Sub
Private Sub frmUpdateSalary_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
SalesStaffComboBox.DataSource = aCustomers.Items
SalesStaffComboBox.DisplayMember = "First_Name"
SalesStaffComboBox.ValueMember = "ID"
End Sub
Private Sub SalesStaffComboBox_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SalesStaffComboBox.SelectedIndexChanged
'fill the textboxes
'Populate ID textbox with selected customer
IDTextBox.Text = SalesStaffComboBox.SelectedValue.ToString
End Sub
To select a value form a combobox, listbox or dropdownlist.
If cmbBox.selectedIndex <> -1 Then
comboIndex = cmbBox.selectedIndex
End Else
cmbBox.Items.removeAt(x)
to remove the item at the selected index
If cmbBox.selectedIndex <> -1 Then
comboItem= cmbBox.SelectedItem()
Without VS10 to check if those are the correct method names or caps But its essentially it
Your combobox has two data variables for each item, the value and the display.
So for each customer you have the name and his ID (You don't specify if it is the last or the first name).
If in its textbox you say:
txtID.Text=cbo.SelectedValue.ToString
txtLastName.Text=cbo.SelectedValue.ToString
txtFirstName.Text=cbo.SelectedValue.ToString
You will get the same result for each textbox, since the left side is always the same.
If in your Combobox the Display Value is a combination of LastName and FirstName you can have:
txtID.Text=cbo.SelectedValue.ToString
txtName.Text=cbo.SelectedText.ToString
I am writing without visual studio so, sorry if I have any minor errors
You don't explain what is aCustomers but I imagine that the whole information for the customers are there. So you can retrieve the data with the id that you already have.
If you give as more info we can help.