kamyk
kamyk

Reputation: 295

C# List in Class - how to show everything in DataGridView

I have a problem, and I don't know how to solve it. I have searched for few hours but I stuck.

I have a class:

public class MyClass
    {
        (...)  

    public MyClass(string name1, string name2, List<MyClass2> name3)
        {
            (...)
        }
    }

public class MyClass2
    {
        (...)
        public MyClass2(int number, string name4)
        {
            (...)
        }
    }

And the question is - how to put MyClass into DataGridView in a way that DataGridView can display the columns with names from MyClass and MyClass2? Is it possible?

Upvotes: 0

Views: 103

Answers (1)

K_Ram
K_Ram

Reputation: 377

This is a little trickier in a DataGridView. Typically I would recommend something like two DataGridViews side by side, one for the list of MyClass, and one for the list of MyClass2s that reside in the active row's databound object (an instance of MyClass) in the MyClass DataGridView. Then I would set the 'selected row changed' event so that when you clicked on a row in the first DataGridView, the sublist of MyClass2s would appear in second DataGridView. It's elegant, and it works.

If you're looking for proper subrows, that's going to be a lot harder in a DataGridView. I'd suggest spoofing it by manually adding a row for the MyClass and two extra columns for the first MyClass2 in the MyClass's list. Then I would repeat that for every MyClass2 in that list.

DataGridViews don't work well with multi-level classes like this, so usually one of those two options works well in its place. I really recommend the first, as it's much simpler.

The concept is similar to what was done in my solution for this question: How to display a dictionary which contains a list in a listBox C#

Upvotes: 1

Related Questions