Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add Groups to ListView, then add Items to Groups

Tags:

c#

.net

winforms

I'm trying to display Groups in my ListView Control and even though I can add them manually in the Designer view, this is not beneficial to me because I need to add items and groups dynamically at runtime, and I couldn't possibly know what groups will be added at runtime.

I've searched online, and to my surprise there is very little information (that makes any kind of sense) that I can find. And the only sample code I could find that looked like it was made for what I want to do is from the offline documentation I downloaded with Visual Studio, and that code sample has 18 compile-time errors and 2 main entry points!

So, how do we dynamically add groups at runtime to a ListView Control, then add items to the list.

So you have a good idea of exactly what I'm trying to accomplish, I've attached an image, below:

ListView with Groups Sample

like image 857
jay_t55 Avatar asked Aug 12 '14 18:08

jay_t55


1 Answers

A way to do this is to add ListViewGroup to your ListView. Then when adding Items to your list view, add a new ListViewItem and specify the group.

public class Form1 {
    private ListViewGroup categoryGroup = new ListViewGroup("Categories", HorizontalAlignment.Left);
    private ListViewGroup movieGroup = new ListViewGroup("Movies", HorizontalAlignment.Left);
    private ListViewGroup castGroup = new ListViewGroup("Cast", HorizontalAlignment.Left);

    private void Form1_Load(object sender, EventArgs e)
    {
        ListView1.BeginUpdate();
        ListView1.Groups.Add(categoryGroup);
        ListView1.Groups.Add(movieGroup);
        ListView1.Groups.Add(castGroup);
        ListView1.EndUpdate();
    }

    private void Button1_Click(object sender, EventArgs e)
    {
        ListView1.BeginUpdate();
        Category.GetCategories().ForEach(x => ListView1.Items.Add(new ListViewItem(x.Name, categoryGroup)));
        Movie.GetMovies().ForEach(x => ListView1.Items.Add(new ListViewItem(x.Name, movieGroup)));
        Cast.GetCast().ForEach(x => ListView1.Items.Add(new ListViewItem(x.Names, castGroup)));

        ListView1.EndUpdate();
    }
}

I'm sure there is a more elegant solution to this, but this should give a decent idea of how to add items to the individual groups.

like image 65
bPuhnk Avatar answered Oct 23 '22 11:10

bPuhnk