Results 1 to 9 of 9

Thread: [RESOLVED] assigning a user entered value to a combo box list item

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Jul 2018
    Posts
    16

    Resolved [RESOLVED] assigning a user entered value to a combo box list item

    Hi I am trying to figure out how to assign a value to an item in my combo box so i can use it in later code. I made a simple list to populate my combo box.

    Code:
     For list = 1 To 8
                cmbFloor.Items.Add(list)
                Next
    I then have a text box with a couple error correcting messages because the user has to enter an integer between 0 and 30. I need to assign that number to whatever combo box item is selected. I'm sure i could figure out a long drawn out way of making a variable out of every combo box item but i'm supposed to be using list and arrays for this project. I also tried combining all my error correcting into one statement using AND. it didn't work so I have it broken up into this. It works just not as tidy as i was hoping.

    Code:
    If Not Integer.TryParse(txtRooms.Text, intOccupied) Then
                MessageBox.Show("Number of rooms must be an integer between 0 and 30")
                txtRooms.Focus()
            ElseIf intOccupied < 0 Then
                MessageBox.Show("Number of rooms must be an integer between 0 and 30")
                txtRooms.Focus()
            ElseIf intOccupied > 30 Then
                MessageBox.Show("Number of rooms must be an integer between 0 and 30")
                txtRooms.Focus()
            End If
    The end result is I should be able to save a certain number to each of the 8 items in my combo box and display them in a list box.

    Thanks in advance

  2. #2
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,929

    Re: assigning a user entered value to a combo box list item

    You can read the items from a combobox and put them into an array using a loop:
    Code:
            For i = 0 To cmbFloor.Items.Count - 1
                yourArray(i) = cmbFloor.Items(i)
            Next

    In terms of the If's, you should be using Or to join them together (as any of them being true should cause the message to be shown):
    Code:
            If (Not Integer.TryParse(txtRooms.Text, intOccupied)) Or intOccupied < 0 Or intOccupied > 30 Then
                MessageBox.Show("Number of rooms must be an integer between 0 and 30")
                txtRooms.Focus()
            End If

  3. #3

    Thread Starter
    Junior Member
    Join Date
    Jul 2018
    Posts
    16

    Re: assigning a user entered value to a combo box list item

    ok so it made a change to what you posted not sure if it matters but probably. i went ahead and changed my list to an array so i could call on it with your code.

    Code:
    Public Module Module1
        Public intArray() As Integer = {1, 2, 3, 4, 5, 6, 7, 8}
        Public Sub array()
    
            For Each intVal As Integer In intArray
                Form1.cmbFloor.Items.Add(intVal)
            Next
        End Sub
    End Module
    and its used like this

    Code:
    Public Class Form1
        Public Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            'declare constants
            Const intRooms As Integer = 30
            'populate combo box for user to select floor using an array
            array()
    
        End Sub
    
    
    
    
        Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
            'declare variables
            Dim intOccupied As Integer
            For i = 0 To cmbFloor.Items.Count - 1
                intArray(i) = CInt(cmbFloor.Items(i))
            Next
            If Not Integer.TryParse(txtRooms.Text, intOccupied) Or intOccupied < 0 Or intOccupied > 30 Then
                MessageBox.Show("Number of rooms must be an integer between 0 and 30")
                txtRooms.Focus()
    
            End If
    
        End Sub
    End Class
    notice it came up with an error and recommended i change it to CInt(cmbFloor.Items(i))

    I'm going through my book scratching my head on how to deploy this though. is it just i = intOccupied?

    really sorry if I'm asking really dumb questions. I'm trying to do school while working full time. I'm off today for the first time in a while and trying to catch up.

  4. #4
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,929

    Re: assigning a user entered value to a combo box list item

    Quote Originally Posted by Frank87 View Post
    ok so it made a change to what you posted not sure if it matters but probably. i went ahead and changed my list to an array so i could call on it with your code.
    It's actually irrelevant, but not a bad thing to do... I would however recommend changing the name of the Sub, because 'array' doesn't make it clear what it does (I'd recommend something like FillFloorsComboFromArray).

    notice it came up with an error and recommended i change it to CInt(cmbFloor.Items(i))
    That was the correct thing to do... I intentionally left that out to make things easier to understand (based on the assumption you had an option turned off, but it turns out you've got it on - which is good).

    I'm going through my book scratching my head on how to deploy this though. is it just i = intOccupied?
    When it comes to working out what code you should write, the first thing to do is forget about code - think about the steps that need to be done (just like if you were doing the work without a computer) and maybe write them down, and only when you know the steps should you try converting them to code.

    In this case you have a value (which came from the textbox), and an array of items, and a combobox with values in... what is it that you actually want to achieve, and what are the steps involved in making that happen?

    When you get to converting the steps in to code, you may find cmbFloor.SelectedIndex and/or cmbFloor.SelectedItem useful.

  5. #5

    Thread Starter
    Junior Member
    Join Date
    Jul 2018
    Posts
    16

    Re: assigning a user entered value to a combo box list item

    ok so got all that working. corrected a couple of small things as well. now my problem is I need to update my list box. by that I mean if i entered 15 rooms on floor 2 and then again entered 13 rooms on floor 2 I need to update what just got dumped into my listbox instead of just adding another line. so with 8 floors i should only be able to have a maximum of 8 items in my list box. I also have to find a way to save all my intOccupied and update that as it goes along. all of those numbers will have to be added for a total at the end of the program.

    so this gives me the correct result in my list box. I tried writing an if statement for lstData.items.contains(cmbFloor.selectedIndex) and i didn't get any errors but i also couldn't make it do anything. I was attempting to have that trigger and remove 1 item from the listbox so it could be replaced or "updated"
    Code:
     Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
    
    
            For i = 0 To cmbFloor.Items.Count - 1
                intArray(i) = CInt(cmbFloor.Items(i))
            Next
            If Not Integer.TryParse(txtRooms.Text, intOccupied) Or intOccupied < 0 Or intOccupied > 30 Then
                MessageBox.Show("Number of rooms must be an integer between 0 and 30")
                txtRooms.Focus()
            Else calculate()
                lstData.Items.Add("Floor: " & cmbFloor.SelectedIndex + 1 & "    Rooms Occupied: " & intOccupied &
                                  "    Occupancy Rate: " & dblPercent.ToString("P2"))
    
            End If

  6. #6
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,299

    Re: assigning a user entered value to a combo box list item

    The Items property of a ListBox is just like any other list. If you want to replace an item you simply set the item at that index. For instance, if you do this:
    vb.net Code:
    1. myListBox.Items.Add("First")
    2. myListBox.Items.Add("Second")
    3. myListBox.Items.Add("Third")
    you'll see the three items "First", "Second" and "Third" in the ListBox. If you then do this:
    vb.net Code:
    1. myListBox.Items(1) = "Hello World"
    the item previously at index 1, i.e. "Second", will be replaced by "Hello World".

    In the code you posted, this part doesn't make sense:
    Code:
            If Not Integer.TryParse(txtRooms.Text, intOccupied) Or intOccupied < 0 Or intOccupied > 30 Then
                MessageBox.Show("Number of rooms must be an integer between 0 and 30")
                txtRooms.Focus()
            Else calculate()
                lstData.Items.Add("Floor: " & cmbFloor.SelectedIndex + 1 & "    Rooms Occupied: " & intOccupied &
                                  "    Occupancy Rate: " & dblPercent.ToString("P2"))
    
            End If
    An 'If...Else' block works on the principle that a condition is tested and if that condition is true then the first action is performed and if it's false then the other action is performed. I don't know what your 'calculate' method does but, based on that code, it seems like you want to do one of two possible things:

    1. Execute calculate as part of the alternate action if the condition is false.
    2. If the first condition is false, test the result of 'calculate' as a second condition and perform an alternate action only if that's true.

    Either way, your code is wrong. If you want the first option then it should be:
    vb.net Code:
    1. If Not Integer.TryParse(txtRooms.Text, intOccupied) Or intOccupied < 0 Or intOccupied > 30 Then
    2.     MessageBox.Show("Number of rooms must be an integer between 0 and 30")
    3.     txtRooms.Focus()
    4. Else
    5.     calculate()
    6.     lstData.Items.Add("Floor: " & cmbFloor.SelectedIndex + 1 & "    Rooms Occupied: " & intOccupied &
    7.                       "    Occupancy Rate: " & dblPercent.ToString("P2"))
    8.  
    9. End If
    and if you want the second option then it should be:
    vb.net Code:
    1. If Not Integer.TryParse(txtRooms.Text, intOccupied) Or intOccupied < 0 Or intOccupied > 30 Then
    2.     MessageBox.Show("Number of rooms must be an integer between 0 and 30")
    3.     txtRooms.Focus()
    4. ElseIf calculate() Then
    5.     lstData.Items.Add("Floor: " & cmbFloor.SelectedIndex + 1 & "    Rooms Occupied: " & intOccupied &
    6.                       "    Occupancy Rate: " & dblPercent.ToString("P2"))
    7.  
    8. End If
    Also, as the documentation states, you should not be calling the Focus method of a control but rather the Select method.

    Finally, you should pretty much always use AndAlso and OrElse in preference to And and Or. Only use the latter when you specifically need to avoid short-circuiting. If you don't know the difference, read the documentation for those operators to learn.

  7. #7

    Thread Starter
    Junior Member
    Join Date
    Jul 2018
    Posts
    16

    Re: assigning a user entered value to a combo box list item

    ok so now I have my totals adding up but still have no way to prevent duplicates. I actually have the program finished if not for this.

    Code:
    Public Class Form1
        Public Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            'populate combo box for user to select floor using an array
            Floors_to_Combo()
    
        End Sub
    
    
    
    
        Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
    
    
            For i = 0 To cmbFloor.Items.Count - 1
                intArray(i) = CInt(cmbFloor.Items(i))
            Next
            If Not Integer.TryParse(txtRooms.Text, intOccupied) Or intOccupied < 0 Or intOccupied > 30 Then
                MessageBox.Show("Number of rooms must be an integer between 0 and 30")
                txtRooms.Focus()
            Else calculate()
                lstData.Items.Add("Floor: " & cmbFloor.SelectedIndex + 1 & "    Rooms Occupied: " & intOccupied &
                                  "    Occupancy Rate: " & dblPercent.ToString("P2"))
                'adds rooms to total every time save is clicked
                count()
            End If
    
    
    
        End Sub
    
        Private Sub btnTotal_Click(sender As Object, e As EventArgs) Handles btnTotal.Click
            'displays totals and percentages at bottom of form
            total()
        End Sub
    
        Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
            'clear all labels, text boxes and variables
            clear()
        End Sub
    
        Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
            'closes form
            Me.Close()
        End Sub
    End Class
    and my module holding all my functions and procedures

    Code:
    Public Module Module1
        'declare constants
        Public Const intRooms As Integer = 30
        Public Const intHotel As Integer = 240
        'declare variables
        Public intOccupied As Integer
        Public dblPercent As Double
        Public intTotal As Integer
        Public dblHotelOccupied As Double
        'build array
        Public intArray() As Integer = {1, 2, 3, 4, 5, 6, 7, 8}
    
        Public Sub Floors_to_Combo()
            'used for populate combo box
            For Each intVal As Integer In intArray
                Form1.cmbFloor.Items.Add(intVal)
            Next
        End Sub
        Public Sub calculate()
            'calculates occupancy rate
            dblPercent = (intOccupied / intRooms)
        End Sub
    
    
        Public Sub total()
            'post totals and percents to labels at bottom of form
            Form1.lblTotal.Text = CType(CInt(intTotal), String)
            Form1.lblRate.Text = (dblHotelOccupied.ToString("P2"))
        End Sub
        Public Sub count()
            'running count for total rooms occupied and percentage of rooms occupied
            intTotal += intOccupied
            dblHotelOccupied = (intTotal / intHotel)
        End Sub
        Public Sub clear()
            'clears everything on form
            Form1.lblRate.Text = ""
            Form1.lblTotal.Text = ""
            intTotal = 0
            intOccupied = 0
            dblHotelOccupied = 0
            dblPercent = 0
            Form1.txtRooms.Clear()
            Form1.lstData.Items.Clear()
            Form1.cmbFloor.SelectedIndex = -1
        End Sub
    End Module
    I know I could change it so you can't select the same floor twice from my combo box but my instructions say that the user should be able to select the same floor and edit the number of rooms. I have found this exercise posted in a couple different forums but It would appear my book has different directions. I can't find an example of this.

  8. #8

    Thread Starter
    Junior Member
    Join Date
    Jul 2018
    Posts
    16

    Re: assigning a user entered value to a combo box list item

    ok i changed some of my code to make it I would assume more proper. However i can't just say i'm going to change items in my listbox based on index. the items are added to the list box from a combo box. the selected index of the items selected from the combo box can be random. meaning i have 1 through 8 in my combo box. i can select 8 and it would be the first one in my listbox and could be followed by 5. If i select 8 or 5 again i need the index of the listbox containing that to be changed. and its funny that you mention about my calculate function being after else. when i use integer.tryparse to convert text box input into a variable and for error correcting it always seems to still do the conversion. my calculate function is simply dblPercent = (intOccupied / intRooms) and intOccupied comes from integer.tryparse. so even though it skips that when an entry is correct it still converts to give me my intRooms variable. I always wondered why it worked but never argued. but i have also typed that in alot of programs the same way and my professor never said a word....for whatever that might be worth lol.

  9. #9
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,299

    Re: assigning a user entered value to a combo box list item

    If you need to know the index of an item in a list then that's what the IndexOf method is for.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width