vb.net Set listbox items equal to an integer - vb.net

I have a list box with lots of options (198 to be exact) and they are names of items.
I need to convert each name to be equal to an integer (the item id) so I can write that number to a file.
For example, if they selected the first item, then the integer would be set equal to 3000 but if they picked the second item, it would be 3001 and so on.
I hope you can understand, wasn't sure how to word it. Thanks.

Create an ENUMERATION and assign each item a value such as below
Public Enum MyCountryCodes As Integer
drzCOUNTRY_UNKNOWN = 0
drzCOUNTRY_AFGHANISTAN = 1
drzCOUNTRY_ALBANIA = 2
drzCOUNTRY_ALGERIA = 3
drzCOUNTRY_AMERICANSAMOA = 4
drzCOUNTRY_ANDORRA = 5
... etc etc
drzCOUNTRY_YEMEN = 241
drzCOUNTRY_ZAMBIA = 242
drzCOUNTRY_ZIMBABWE = 243
End Enum

You mean like this ?
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
MsgBox(ListBox1.SelectedIndex + 3000)
End Sub

Assign a dataTable to the ItemSource of your listBox. The DataTable can obviously have more than one field in it. You'll have to configure the properties of the list box to set one of it's fields (the string to display) as visible, then have the other field as visible = false. In one of the events (such as selectedItemChange i think) access the item's SelectedItem that corresponds to the id field.

Related

TextBox value equals with value from a database

I have a Northwind database and when i want to change or put a new name at a textbox where the names of the ships are, my program to check all the names that already exist in the database and if there is not this name then to show me a message. I created a new table with only the ship names with fill and get commands. I don't know where is my mistake on the code.
Private Sub ShipNameTextBox_Validating(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles ShipNameTextBox.Validating
For i As Integer = 0 To NorthwindDataSet.Orders1.Rows.Count - 1
If Not (ShipNameTextBox.Text = Convert.ToString(NorthwindDataSet.Orders1.Rows(i))) Then
MessageBox.Show("The boat name should be one of the list")
ShipNameTextBox.Focus()
End If
Next
End Sub
You can use DataTable Select() method like below which will return a DataRow[] (assuming that your datatable have a column name shipname)
DataRow[] rows = NorthwindDataSet.Orders1.Select("shipname = " + ShipNameTextBox.Text.Trim())
Then you can just check if the returned DataRow array has any rows. If filter condition doesn't match them it will be empty
if(rows.Length > 0)
{
MessageBox.Show("The boat name should be one of the list")
ShipNameTextBox.Focus()
}

Trying to move items from one to the other

]I am having strange problem when i try to move items from one grid view to another using a bindingsource it adding in an extra blank row some reason
Private Sub btnMove_Click(sender As System.Object, e As System.EventArgs) Handles btnMove.Click
Dim bs As New BindingSource
Dim a As Integer
Dim removeList As List(Of infoRemoteFiles) = fileList
For a = 0 To grdAvailFiles.SelectedRows.Count
grdProcessFiles.Rows.Add(grdAvailFiles.Rows(a).Cells("filename").Value)
removeList.RemoveAll(Function(p As infoRemoteFiles) p.filename = grdAvailFiles.Rows(a).Cells("filename").Value)
Next
bs.DataSource = removeList
grdAvailFiles.DataSource = bs
End Sub
please see what i mean its the row below what I have selected I dont no where its comming from thanks
The extra blank row is added automatically if you have the AllowUserToAddRows property set to True on the DataGridView control.
From the documentation:
If the DataGridView is bound to data, the user is allowed to add rows if both this property and the data source's IBindingList.AllowNew property are set to true.
On a separate note, you shouldn't have to create anew binding source (for the source data grid). Instead, modify the collection that is already bound to the DataSource property.
Try:
For A = 0 To grdAvailFiles.SelectedRows.Count - 1
Note the minus 1, because you're starting from zero.

VB.NET Iterating Form Labels

I have several label boxes on my design form that all share the naming convention lbl_#.text where # ranges from 1 to 60. I want to make a loop that iterates through each lbl_#.text adding some incremental value, let's say multiples of 2 for this question's theoretical purpose.
Something such that the end result would amount to the following:
lbl_1.text = "2"
lbl_2.text = "4"
lbl_3.text = "6"
...
lbl_60.text = "120"
I'm not sure how to access each of these labels through the coding side, I only know how to explicitly mention each label and assign a value :/
There are a few options here.
In this situation the labels will often have a common container, such as panel or groupbox control. In that case:
Dim formLabels = myContainerControl.Controls.OfType(Of Label)()
For Each formLabel As Label In formLabels
'...
Next formLabel
Of course, this mixes logical groups with visual groupings. Those two things don't always align well, so you can also...
Add them all to a Label array (or List(Of Label) or any other enumerable):
Dim formLabels(60) As Label = {lbl_1, lbl_2, lbl_3 .... }
For Each formLabel As Label in formLabels
'...
Next formLabel
But sometimes that's more trouble than it's worth, even if you use a loop to create the collection, and so you can also
Use the .Name property (in conjunction with a naming convention to identify your desired controls):
Dim formLabels = Controls.Where(Function(c) c.Name.StartsWith("lbl_"))
For Each formLabel As Label In formLabels
'...
Next formLabel
Some combination of the above (for example, code in the form load event to create a list based on the name property).
Notice the actual For Each loop is exactly the same in all of those options. No matter what you do, get to the point where you can write a single expression to identify the label control, and then run a simple loop over the expression result.
This points to a final strategy: think in terms of binding to a data source. With a data source, your labels are created as part of a DataGridView, FlowLayoutPanel, or similar control. Then you can iterate the rows in the grid or panel.
Use the Controls collection:
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim i As Integer
For i = 1 To 3
Dim myLabel As Label = CType(Me.Controls("lbl_" & i), Label)
myLabel.Text = ...whatever value you want to put here
Next
End Sub
End Class
If you don't know how many labels there are, one option is to use a Do Loop.
Dim lblTarget As Label = Nothing
Dim intCursor As Integer = 1
Dim bolFirstIteration As Boolean = True
Do Until lblTarget Is Nothing AndAlso Not bolFirstIteration
If bolFirstIteration Then
bolFirstIteration = False
End If
lblTarget = CType(Me.Controls("lbl_" & intCursor.ToString()), Label)
If Not lblTarget Is Nothing Then
lblTarget.Text = (intCursor * 2).ToString()
End If
intCursor += 1
Loop

VB 2010 array/write array to file

I'm close to getting this to work, but currently can't get any output to display in the listbox. I had it working, but needed to move some things around to get the join function to work.
In my program, a user enters input into a textbox and an array is displayed in a listbox based on what they type in. For example, if they type in "a", all foods (in the textfile that is connected to the program) that start with "a" will be displayed.
When there is output, I need to find a way to name this array (which is created based on what the user inputs) and join all of the items in the listbox (example: foods stacked on top of each other in the listbox will be shown at the bottom as a string).
I am posting the code that I have thus far; all of the errors that I'm getting (and potentially my logic errors) are just in the first public class until the end of the first if-next statement:
Public Class frmFoods
Dim foods() As String = IO.File.ReadAllLines("foods.txt")
Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplay.Click
Dim Letter As String = txtLetter.Text.ToUpper
Dim smallerarray() As Array
Dim userarray As String
lstOutput.Items.Clear()
If IsNumeric(txtLetter.Text) = False Then
For Each food As String In foods
smallerarray = listfoods(Letter)
lstOutput.Items.Add(Letter)
userarray = Join(smallerarray, ", ")
lstOutput.Items.Add(userarray)
Next
ElseIf IsNumeric(txtLetter.Text) = True Then
MessageBox.Show("Please enter a letter.")
Else
MessageBox.Show("The text box is empty")
End If
End Sub
Function listfoods(ByVal letter As String) As String()
Dim foodarray(foods.Count - 1) As String
Dim counter As Integer = 0
For Each food As String In foods
If food.StartsWith(letter) Then
foodarray(counter) = food
counter += 1
End If
Next
ReDim Preserve foodarray(counter - 1)
Return foodarray
End Function
you need to save the results of the listfoods function in a dictionary or similar and associate it with a key if you want to 'Name' it, although its not clear why you need to do this
As for listing the foods starting with the particular letter, you just need to iterate your result of the function listfoods and separate each one by a comma don't you?
What you have now will create many lists of each food as you are getting the list of food beginning with a particular letter for each food.. As I understand the question you only need to do that once.
Example:
Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplay.Click
Dim Letter As String = txtLetter.Text.ToUpper
Dim smallerarray() As Array
Dim userarray As String
lstOutput.Items.Clear()
If IsNumeric(txtLetter.Text) = False Then
'get all items from the file which begin with the letter the user chose
smallerarray = listfoods(Letter)
'add that letter to the output listbox
lstOutput.Items.Add(Letter)
'join all of the elements which begin with that letter
'into a single comma separated string
userarray = Join(smallerarray, ", ")
'add that string to the output
lstOutput.Items.Add(userarray)
ElseIf IsNumeric(txtLetter.Text) = True Then
MessageBox.Show("Please enter a letter.")
Else
MessageBox.Show("The text box is empty")
End If
End Sub
it would probably be useful for you to step through the code and see the values of the variable at each place and compare this with what you expect to see if you can see where the actual value differs from what your logically expect so you can start to identify where the issue is

Listbox.selected index change variable assignment

Hi there
What is the correct way of assigning the selected index's value from a listbox to a variable? The user selects an item in a listbox and then the output changes depending on their selection.
I use:
variablename = listbox.text
in the listBox_SelectedIndexChanged event and this works.
When I use the button_click event I use:
variablename = listbox.selectedindex
But this does not work in the listbox_selectedindexchanged event.
Please could you let me know if it is okay to use it like I did above or if I will run into problems and why you cannot use the selectedindex method.
Thanks!
A. It sounds like your variable is a string, and yet you are trying to assign to it the value returned by the SelectedIndex Property, which is an integer.
B. If you are trying to retrieve the value of the item associated with the SelectedINdex of the Listbox, use the Index to return the Object itself (the listbox is a list of Objects, which are often, but not always, going to be strings).
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
'THIS retrieves the Object referenced by the SelectedIndex Property (Note that you can populate
'the list with types other than String, so it is not a guarantee that you will get a string
'return when using someone else's code!):
SelectedName = ListBox1.Items(ListBox1.SelectedIndex).ToString
MsgBox(SelectedName)
End Sub
THIS is a little more direct, using the SelectedItem Property:
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
'This returns the SelectedItem more directly, by using the SelectedItem Property
'in the event handler for SelectedIndexChanged:
SelectedName = ListBox1.SelectedItem.ToString
MsgBox(SelectedName)
End Sub
Well it depends what you want to achieve from the listbox's selected item.
There are a couple of possible ways, let me try to explain some of these for your homework.
Suppose you have a data table with two columns, and their rows...
ID Title
_________________________
1 First item's title
2 Second item's title
3 Third item's title
And you bind this data table to your list box as,
ListBox1.DisplayMember = "ID";
ListBox1.ValueMember = "Title";
If user selects second item from the list box.
Now if you want to get the display value (Title) of the selected item, then you can do
string displayValue = ListBox1.Text; // displayValue = Second item's title
OR even this to get same results.
// displayValue = Second item's title
string displayValue = ListBox1.SelectedItem.ToString();
And to get the value member against the selected item, you need to do
string selectedValue = ListBox1.SelectedValue; // selectedValue = 2
Now there are situations when you want to allow user to select more than one item from the list box, so you then set
ListBox1.SelectionMode = SelectionMode.MultiSimple;
OR
ListBox1.SelectionMode = SelectionMode.MultiExtended;
Now suppose if user selects two items; second and third.
So you can get the display values by simply iterating through the SelectedItems
string displayValues = string.Empty;
foreach (object selection in ListBox1.SelectedItems)
{
displayValues += selection.ToString() + ",";
}
// so displayValues = Second item's title, Third item's title,
And if you want to get ID's instead of Title's then...
I am also looking through it, I will post if found.
I hope your understandings build.
Good Luck!