Search code examples
c#winformslistviewlistviewitemlistviewgroup

Adding groups and items to ListView in C# windows form


I'm trying to create a ListView in Windows Form that contains groups and items i get from DataBase.

My ListView is called "lstItems"

In the begining, the ListView is empty and I fill it with data during the runnig of the program.

This is the code I use to create the groups:

foreach(DataRow r in tasksTbl.Rows)
{
    string groupName = "group" + num;
    num++;
    lstItems.Groups.Add(groupName, r.Field<string>(0));
}

The tasksTbl table is not empty and it creates several group that I cannot see on the screen at this point.

This is the code I use to create the items and subItems for the groups:

private void CreateItem(DataTable tbl)
{
    int taskId = tbl.Rows[0].Field<int>(0);
    string taskName = tbl.Rows[0].Field<string>(1);
    DateTime startDate = tbl.Rows[0].Field<DateTime>(2);
    DateTime endDate = tbl.Rows[0].Field<DateTime>(3);

    string dateStr = startDate.ToString() + " - " + endDate.ToString();

    ListViewItem item = new ListViewItem(dateStr);
    item.Tag = taskId.ToString();

    foreach (DataRow r in tbl.Rows)
    {
        string position = r.Field<string>(5);
        string soldier = r.Field<string>(6);
        item.SubItems.Add(soldier + " (" + position + ")");
    }

    foreach(ListViewGroup grp in lstItems.Groups)
        if (grp.Header.Equals(taskName))
            grp.Items.Add(item);
}

Here also the tbl table is not empty and it creates the items and sub items to each group.

I can see in the debugger that the groups has the items properly.

My problem is that I cannot see the groups or the items on the screen.

What am I missing?

Can someone give me a hand?

Thank you in advance!


Solution

  • I figured out my problem.

    I needed to add columns to the ListView and then, to add the items to the ListView and only in the end to add the items to the groups.

    I did it and now it works.