Multiple listbox selections-VBForums
Results 1 to 18 of 18

Thread: Multiple listbox selections

  1. #1

    Thread Starter
    New Member
    Join Date
    Oct 2017
    Posts
    7

    Multiple listbox selections

    First off I would like to say that I am completely new to VB.Net so forgive me if this question seems fairly simple.

    I'm currently working on a project with multiple list boxes, that are populated when the form loads. 1 list box is visible, the other 3 are hidden. What I'd like to be able to do is if the user clicks on the item within the first listbox, it highlights the corresponding rows of the 3 hidden boxes. (the same goes with a next item option I'm working on, but one issue at a time...haha) I'm sure this is fairly simple and I'm just overthinking the situation, but I've been trying to "self teach" by using search engines and it isn't helping as much as I thought it would. Any help would be greatly appreciated.

    Thanks!

  2. #2
    Member
    Join Date
    Jul 2017
    Location
    Exeter, UK
    Posts
    45

    Re: Multiple listbox selections

    Well you can simply iterate through each of the 'hidden' lists looking for a match, but as they are hidden you will not see that.

  3. #3
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    96,578

    Re: Multiple listbox selections

    Define a type that has four properties. Populate an array or collection with instances of that type. Bind the array or collection to each ListBox, i.e. assign it the DataSource property, and set the DisplayMember of each ListBox to the name of a different property. The rest happens automatically. Making a selection in any ListBox will automatically select the same item in all the others.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    MSDN "How Do I?" Videos: VB | C#
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  4. #4
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    3,809

    Re: Multiple listbox selections

    I don't get the point. If the 3 ListBoxes are hidden, how will you tell if the right thing is selected? If you just want to know, "Do these 3 lists contain this value?" why do you think you need hidden ListBoxes?

    What is the real problem you're trying to solve? 99 times out of 100 when someone is using hidden controls, they're trying to solve a different problem and haven't quite figured out Controls aren't the only data structure available.
    Nothing I post is production-ready. It is provided as-is, use it at your own risk.

  5. #5

    Thread Starter
    New Member
    Join Date
    Oct 2017
    Posts
    7

    Re: Multiple listbox selections

    I'll go into more detail (I should've in the previous post), I have 4 listboxes, each populated as the form loads with list1.items.add("value") etc, the 3 boxes I have hidden (they are hidden for purely aesthetic purposes), I can control whether or not they're visible or not (currently they're not visible), I will make them visible to test the selection process though, but what I'm reading is that an array (four of them) is required and to bind each array to the list box that it's associated with?

    And if that's the case, I do not require the list1.items.add("value") to build the boxes on start up then?

    I'm using Visual Studio 15 to build this as an fyi
    Last edited by Xandler; Oct 9th, 2017 at 11:41 AM.

  6. #6
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    30,824

    Re: Multiple listbox selections

    The key question is whether or not you ever intend those other listboxes to be visible. If you don't, then you shouldn't use listboxes for that. Controls have a certain amount of overhead that there is no good reason to pay if you don't need to. The cost (in performance and memory) for a control is utterly trivial, but it will add up if you have enough of them. Therefore, if you will never have the listboxes visible, then there are better options. If you do expect to have them visible at times, or if the goal is to allow the user to make decisions that will cause different listboxes to become visible, or anything like that, then the listboxes may be the best solution.

    Having said that, I would also note that there is another option you might consider, which is to use either a ListView or a DataGridView. Of those, the latter would be FAR more common. A DGV is essentially a grid with a lot of customization possible. So, you could have your four columns, and hide three of them. Of course, there wouldn't be any independent scrolling in a grid, as you would have with four listboxes, but that may not be a big deal. The real benefit is that your goal is obtained automatically with a grid: When you select something, you are selecting the row, and whether the other columns are visible or not hardly matters.

    However, if you still want the listboxes, then you kind of want an array, but more likely you want a List(of T). Arrays are fixed size, so you use them when you know the number of elements in advance. You may know that, or not, you haven't said, and it barely matters. A List is the thing to use if the number of items isn't fixed, an array is the thing to use if the number of items IS fixed.

    What JMC was talking about was not four arrays, but one array (or List). However, the array is an array of some type that you would create. This type would probably be a class with four properties for the four elements. You DO have to make them properties, but by VS2015, this was super easy, as it could be as simple as this:
    Code:
    Public Class MyType
      Public Property Element1 As WhateverType
      Public Property Element2 As WhateverType
      Public Property Element3 As WhateverType
      Public Property Element4 As WhateverType
    End Class
    Your array would be an array of MyType, in this case. You could then bind the array to all four listboxes, and set a different DisplayMember for each one, which would just be the name of a property:
    Code:
    ListBox1.DisplayMember = "Element1"
    ListBox1.DataSource = YourArrayOrListHere
    Then they all stay syncronized...but a DGV would likely be better, in that case.
    My usual boring signature: Nothing

  7. #7
    Fanatic Member ChrisE's Avatar
    Join Date
    Jun 2017
    Location
    Frankfurt
    Posts
    564

    Re: Multiple listbox selections

    Hi,
    what is in Listbox1 ? that relates to Listbox2 and so on....

    have you thought about a Listview rather that Listboxes

    here a sample with Listview
    add somthing with calculation
    Code:
    Public Class Form1
    
        Public Sub lvwAddItem(ByVal lvw As ListView, ByVal ParamArray Text() As String)
            'Then Call
            'lvwAddItem(ListView1,"Text1","Text2,"Text3","Text4")
            With lvw.Items
                .Add(New ListViewItem(Text))
            End With
        End Sub
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    
            With ListView1
                .View = View.Details
                .LabelEdit = False
                .HideSelection = False
                .GridLines = True
                .FullRowSelect = True
                .Columns.Add("Student", 120)
                .Columns.Add("Age", 80)
                .Columns.Add("Birthday", 80)
            End With
            lvwAddItem(ListView1, "Sammy", IsAgeGet, "02.02.1996")
            lvwAddItem(ListView1, "Mary", IsAgeGet, "02.02.1992")
            lvwAddItem(ListView1, "Tom", IsAgeGet, "02.02.1990")
            lvwAddItem(ListView1, "Chris", IsAgeGet, "02.02.1988")
    
            Dim IsAge As Integer
            For Each itm As ListViewItem In ListView1.Items
                IsAge = GetPersonAge(itm.SubItems(2).Text, Now())
                itm.SubItems(1).Text = IsAge
            Next
        End Sub
        Public Shared Function GetPersonAge(ByVal birthdate As DateTime, ByVal AgeOnThisDate As DateTime) As Integer
            Dim age As Integer = AgeOnThisDate.Year - birthdate.Year
            If AgeOnThisDate.Month < birthdate.Month OrElse (AgeOnThisDate.Month = birthdate.Month AndAlso AgeOnThisDate.Day < birthdate.Day) Then
                age -= 1
            End If
            If age < 0 Then
                Return 0
            Else
                Return age
            End If
        End Function
    
        Public Function IsAgeGet()
            'Placeholder for Calc
            IsAgeGet = ""
        End Function
    regards
    Chris
    to hunt a species to extinction is not logical !
    since 2010 the number of Tigers are rising again in 2016 - 3900 were counted. with Baby Callas it's 3901, my wife and I had 2-3 months the privilege of raising a Baby Tiger.

  8. #8

    Thread Starter
    New Member
    Join Date
    Oct 2017
    Posts
    7

    Re: Multiple listbox selections

    The first Listbox I have contains product descriptions of items (ie, "18 ounce Raisin Bran Crunch"), Listbox2-4 contain things used for calculations such as product id, weight, and cost (these will be used to calculate shipping, sales tax, etc)

  9. #9
    Fanatic Member ChrisE's Avatar
    Join Date
    Jun 2017
    Location
    Frankfurt
    Posts
    564

    Re: Multiple listbox selections

    Hi,

    I think you should consider using a Database
    you will also want to write an Invoice etc....

    regards
    Chris
    to hunt a species to extinction is not logical !
    since 2010 the number of Tigers are rising again in 2016 - 3900 were counted. with Baby Callas it's 3901, my wife and I had 2-3 months the privilege of raising a Baby Tiger.

  10. #10
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    3,809

    Re: Multiple listbox selections

    Quote Originally Posted by Xandler View Post
    The first Listbox I have contains product descriptions of items (ie, "18 ounce Raisin Bran Crunch"), Listbox2-4 contain things used for calculations such as product id, weight, and cost (these will be used to calculate shipping, sales tax, etc)
    Aha! This is exactly what I meant.

    Think about me, a magical unicorn. I have a name. I have a wallet. I have some eyeballs. But I am not "one element in a list of names, one element in a list of wallets, and one element in a list of eyeballs". I'm a single being with all of those things.

    VB .NET is designed to help you write code that recognizes that. When you find yourself wanting to work with bits of data that are all related, you're supposed to write a class. You just described a class with four pieces of information:
    Code:
    Public Class Item
        Public Property Description As String
        Public Property Id As Integer
        Public Property Weight As Double
        Public Property Cost As Integer
    End Class
    One secret that almost no one learns about VB is that ListBox was cleverly designed to work with objects like this, not just Strings. You can totally add this Item class to a ListBox. Working with it is a little clunky, because ListBox is nearly 15 years old and it predates some useful features. But with a little bit of work you can make it happen.

    One of the tricks is you have to set the ListBox's DisplayMember property. It expects a String that is the name of one of the properties of the objects it contains. If you do not set this, the .ToString() method will be called, and that usually results in something like "{WindowsApplication45.Item}". You don't want that. Instead, set DisplayMember to "Description" and you'll get the item description.

    For this very brief example, make a new project. Drag a ListBox onto it. Drag a Label on to it. The code is going to add some items at startup. When you click on an item, the Label will be updated to display the other properties of the item. Read the comments, they explain the parts that can be a little tricky.
    Code:
    Public Class Form1
    
        Protected Overrides Sub OnShown(e As EventArgs)
            MyBase.OnShown(e)
    
            ' I like to set DisplayMember in code, near where I add items. It's                   
            ' easy to forget to do it in the designer.
            ListBox1.DisplayMember = "Description"
    
            ListBox1.Items.Add(New Item() With {
                .Description = "Can of Beans",
                .Id = 1,
                .Weight = 14,
                .Cost = 199
            })
            ListBox1.Items.Add(New Item() With {
                .Description = "Dash of Salt",
                .Id = 2,
                .Weight = 0.1,
                .Cost = 14
            })
    
            Label1.Text = "No item is selected."
        End Sub
    
        Private Sub ListBox1_SelectedIndexChanged(
            sender As Object,
            e As EventArgs) Handles ListBox1.SelectedIndexChanged
    
            Dim selectedIndex = ListBox1.SelectedIndex
    
            ' When the index is -1, no item is selected.
            If selectedIndex = -1 Then
                Label1.Text = "No item is selected."
            End If
    
            ' When the index is not -1, an item is PROBABLY there. It comes out
            ' as an Object, it must be converted to an Item for our purposes.
            Dim selectedItem = TryCast(ListBox1.SelectedItem, Item)
            If selectedItem IsNot Nothing Then
                ' Be paranoid! Always make sure the item isn't Nothing.
                Dim costInDollars As Double = selectedItem.Cost / 100.0
                Dim itemMessage As String =
                    String.Format(
                        "This item has ID {0}, weighs {1} ounces, and costs ${2}.",
                        selectedItem.Id,
                        selectedItem.Weight,
                        costInDollars)
                Label1.Text = itemMessage
            End If
        End Sub
    End Class
    
    Public Class Item
        Public Property Description As String
        Public Property Id As Integer
        Public Property Weight As Double
        Public Property Cost As Integer
    End Class
    This is much easier and more elegant than having hidden ListBoxes or multiple arrays.
    Nothing I post is production-ready. It is provided as-is, use it at your own risk.

  11. #11
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    30,824

    Re: Multiple listbox selections

    Quote Originally Posted by Sitten Spynne View Post
    Think about me, a magical unicorn.
    Well, that IS how I've always seen you
    My usual boring signature: Nothing

  12. #12

    Thread Starter
    New Member
    Join Date
    Oct 2017
    Posts
    7

    Re: Multiple listbox selections

    Well...thanks for all the advice to the people who posted, but apparently arrays aren't supposed to be used for this (I think it would be way better if they would, but I digress). Only listbox view controls can be used (this is for an intro to vb.net course...but this project definitely does not feel like an introductory type thing). I'd go into more details, but I know of quite a few forums (most) that frown upon doing the work of others because it prevents the learning process...but even after reading the chapters relating to this...I'm still pretty stumped on how to do the code for it.

  13. #13
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    3,809

    Re: Multiple listbox selections

    I think someone made a post that uses only ListBox controls to do what you want. You might want to look closer, or explain why it's not exactly what you want. But I do think, given that time is passing, you might also think about if it gives you some inspiration to try other things, because the forums can't always help in a timely manner.

    I can say it's not very likely your teacher wants you to use invisible ListBox controls. I guess if they do, you have to, but no one does that in real code.
    Nothing I post is production-ready. It is provided as-is, use it at your own risk.

  14. #14
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    31,104

    Re: Multiple listbox selections

    Quote Originally Posted by Sitten Spynne View Post
    I think someone made a post that uses only ListBox controls to do what you want. You might want to look closer, or explain why it's not exactly what you want. But I do think, given that time is passing, you might also think about if it gives you some inspiration to try other things, because the forums can't always help in a timely manner.

    I can say it's not very likely your teacher wants you to use invisible ListBox controls. I guess if they do, you have to, but no one does that in real code.
    True, but at the same time, you have to learn to walk before you can run. Also, sometimes it's good to learn the bad way to do something so that you can then see why it's bad, and appreciate why there is a better way.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  15. #15

    Thread Starter
    New Member
    Join Date
    Oct 2017
    Posts
    7

    Re: Multiple listbox selections

    Yea...the instructions for this assignment is pretty weird, but, this is actually in the UI requirements: Use hidden, parallel List Boxes to store Product IDs, Unit Weights and Unit Costs so they are available for calculations.

    Makes no sense to me why they'd want them hidden either but alas!

    Also, I appreciate the response (I've been getting some help from where I work as some people know vb.net), but often times they're busy or like today in meetings most of the morning. This isn't required to be submitted for another 2 weeks, I just like to work ahead, I just don't currently understand how to make like the previous/next item controls scroll through the listbox after the user has selected an item (and have the subsequent rows in the hidden tables selected.) I think it's with a SelectedIndexChanged event...just quite a bit foggy on the coding details...

  16. #16

    Thread Starter
    New Member
    Join Date
    Oct 2017
    Posts
    7

    Re: Multiple listbox selections

    Update: I have figured out the next/previous item with a little help from Google!

  17. #17
    Member
    Join Date
    Jul 2017
    Location
    Exeter, UK
    Posts
    45

    Re: Multiple listbox selections

    To match an item in list1 with items in the other lists you will need a 'key' value in all lists, which presumably will be the product id and in the first column. When a user selects in a item in list1 i.e. the selecteditem, loop though the other lists and for each row check if the product id matches the selected product id.

  18. #18
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    3,809

    Re: Multiple listbox selections

    Ugh. Fair enough. This kind of requirement in assignments would make me question the course, though.

    Here's what I hope you found on Google:

    When you click an item in a ListBox, it will raise its SelectedIndexChanged event. That is a good time to get the SelectedIndex value. That number will tell you the index of the currently selected item. It MIGHT be -1: that means "no item is selected". That usually happens at startup, so it helps to be ready for it because if you ARE using arrays you have to be careful to NOT give them a -1 index.

    So if you have three list boxes with obvious names, you could make sure the 3 hidden ones stay in sync by handling the first one's SelectedIndexChanged event like this:
    Code:
    Private Sub ListBox1_SelectedIndexChanged(...) Handles ...
        Dim selectedIndex As Integer = ListBox1.SelectedIndex
    
        ListBox2.SelectedIndex = selectedIndex
        ListBox3.SelectedIndex = selectedIndex
        ListBox4.SelectedIndex = selectedIndex
    End Sub
    That's how to solve most WinForms problems: you almost always have a sentence:
    When <something happens> I want to <do something>.
    That means looking at the documentation for an event that represents "something happens" and adding "do something" to that event handler.
    Nothing I post is production-ready. It is provided as-is, use it at your own risk.

Posting Permissions

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



Featured


Click Here to Expand Forum to Full Width

Survey posted by VBForums.