Search code examples
c#winformslistboxpicturebox

How to have one list box present data based on selection of first one?


I'm making a windows form with 2 list boxes. My plan is for the user to have the option to add/edit/remove from both list boxes. When a user selects an option from the first list (a selection of car names i.e. Mazda 3), the second list box will show all the data that would be entered based off that of the first selection (my idea is to keep service records for each vehicle; this box also will have the option to add/edit/remove). How should I go about having the second list box show items based on the selection of the first list box?

Is a multidimensional array the best way to do this? I also plan on having a picture box that will show a picture that the user can upload and will be view-able based on the selection of the SECOND list box.

Thanks


Solution

  • I'm not really clear on what it actually is you're trying to do, but from my understanding you have a list of cars, and for every car on that list, there is a list of service records?

    If this is the case you could do something like this:

    public partial class Form1 : Form
    {
    
        List<string> cars = new List<string>()
        {
            "Mazda 3",
            "Mazda 6",
            "VW Polo",
            "VW Golf"
        };
    
        List<string> Mazda3 = new List<string>()
        {
            "12-04-2008",
            "14-03-2010",
            "20-05-2012",
    
        };
    
        List<string> Mazda6 = new List<string>()
        {
            "12-08-2012",
            "14-07-2014",
            "03-09-2016",
        };
    
        List<string> VWPolo = new List<string>()
        {
            "Some Date",
            "Some Date",
            "Some Date",
        };
    
        List<string> VWGolf = new List<string>()
        {
            "Some Date",
            "Some Date",
            "Some Date",
        };
    
        List<List<string>> ServiceLists = new List<List<string>>();
    
    
        public Form1()
        {
            InitializeComponent();
    
            ServiceLists.Add(Mazda3);
            ServiceLists.Add(Mazda6);
            ServiceLists.Add(VWPolo);
            ServiceLists.Add(VWGolf);
    
            Cars_listBox.DataSource = cars;
        }
    
        private void Cars_listBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            ServiceRecords_listBox.DataSource = ServiceLists[Cars_listBox.SelectedIndex];
        }
    }
    

    In this example the listBoxes are created in the designer