How to add subitems to a ListView?

前端 未结 3 1070
时光说笑
时光说笑 2021-01-05 17:57

I\'m trying to get the simplest possible example of a Listview with subitems working. But this code:

private void button1_Click(object sender, EventArgs e) {         


        
相关标签:
3条回答
  • 2021-01-05 18:22

    You need to add another column for the SubItem. The reason why your subitem is not shown is because there is no column for it. Try this one.

    listView1.Columns.Add("Column 1"); // you can change the column name
    listView1.Columns.Add("Column 2");
    string[] strArr = new string[4] { "uno", "dos", "twa", "quad" };
    foreach (string x in strArr)
    {
        ListViewItem lvi = listView1.Items.Add(x);
        lvi.SubItems.Add("Ciao, Baby!");
    }
    
    0 讨论(0)
  • 2021-01-05 18:31

    Try adding the item after adding a subitem:

    ListViewItem lvi = new ListViewItem(strArr[i]);
    lvi.SubItems.Add("Ciao, Baby!");
    listView1.Items.Add(lvi);    
    listView1.Items[i].Group = listView1.Groups[0];
    

    Hope this helps!

    0 讨论(0)
  • 2021-01-05 18:35

    This works for me:

    listView1.Columns.Add("Col1");
    listView1.Columns.Add("Col2");
    
    string[] strArrGroups = new string[3] { "FIRST", "SECOND", "THIRD" };
    string[] strArrItems = new string[4] { "uno", "dos", "twa", "quad" };
    for (int i = 0; i < strArrGroups.Length; i++)
    {
        int groupIndex = listView1.Groups.Add(new ListViewGroup(strArrGroups[i], HorizontalAlignment.Left));
        for (int j = 0; j < strArrItems.Length; j++)
        {
            ListViewItem lvi = new ListViewItem(strArrItems[j]);
            lvi.SubItems.Add("Hasta la Vista, Mon Cherri!");
            listView1.Items.Add(lvi);
            listView1.Groups[i].Items.Add(lvi);
        }
    } 
    

    It turns out that you have to add the items to the groups, and not set the group property on the item, as shown in other questions. Very, very strange.

    The result is:

    enter image description here

    Tested in .Net 4, WinForms, VS2010

    0 讨论(0)
提交回复
热议问题