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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With