简体   繁体   中英

display list items into data grid view c#

I have a super-class (abstract) and then 2 inherited classes.
SuperClass: Sessions
Class 1: Cycling
Class 2: Running

I also have a list that will hold all of my objects
private List<Session> allSessions = new List<Session>();

I also have declared some arrays that hold hard-coded data to populate my objects.

Also, Running and Cycling has an overridden ToString() method that displays different data depending on the class.

public override string ToString() => $"Cycle Average RPM is {AverageRpm} and Average Resistance is {AverageResistance}";

I am using a for loop to create and add new objects into my list like this

            for (int i = 0; i < id.Length; i++)
            {
                Cycling Cycle = new Cycling(id[i], titles[i], date[i], duration[i], difficulty[i], instructor[i],
                    description[i], averageRpm[i], averageResistance[i]);

                // Add new objects to list
                allSessions.Add(Cycle);
            }    

I have a dataGridView that is getting everything from my list and displays it like this: 在此处输入图片说明

My problem now is, that I want to display only specific data depending on what you choose in the ComboBox, but something is not working,

The overridden ToString() is not added to the list for some reason and whenever I choose a different option from the ComboBox, nothing is being displayed.

EDIT 1:

            // Filter Sessions by type using Linq
        var sessions = new List<Session>();
        var cyclingSessions = sessions.OfType<Cycling>();
        var runningSessions = sessions.OfType<Running>();

        listBox1.DataSource = null;
        listBox1.Items.Clear();


        if (cboMenu.SelectedIndex == 0)
        {
            // Populate GridView with data
            dataDisplay.DataSource = allSessions;
        }
        else if (cboMenu.SelectedIndex == 1)
        {
            // Populate GridView with data
            dataDisplay.DataSource = cyclingSessions;
        }
        else
        {
            // Populate GridView with data
            dataDisplay.DataSource = runningSessions;
        }
    }

You need to filter your sessions list and set that as your data source you can easily filter the list using OfType from System.Linq It would look something like this:

var sessions = new List<Sessions>();
var cyclingSessions = sessions.OfType<Cycling>();
var runningSessions = sessions.OfType<Running>();
dataDisplay.DataSource = cyclingSessions;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM