c# – 如何将子项添加到ListView?

前端之家收集整理的这篇文章主要介绍了c# – 如何将子项添加到ListView?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用子项目工作的Listview获得最简单的示例.但是这段代码
private void button1_Click(object sender,EventArgs e) {
    listView1.Groups.Add(new ListViewGroup("Kannst du mich sehen?",HorizontalAlignment.Left));
    string[] strArr = new string[4] { "uno","dos","twa","quad" };
    for (int i = 0; i < strArr.Length; i++)
    {
        ListViewItem lvi = new ListViewItem(strArr[i]);
        listView1.Items.Add(lvi);
        lvi.SubItems.Add("Ciao,Baby!");
        listView1.Items[i].Group = listView1.Groups[0];
    }
}

不显示子项(“Ciao,Baby!”).表明:

Kannst du mich sehen?
---------------------
uno   dos   twa   quad

……但我希望它是:

Kannst du mich sehen?
---------------------
uno Ciao,Baby!
dos Ciao,Baby!
twa Ciao,Baby!
quad    Ciao,Baby!

更奇怪的是(在我看来),我明白了:

Default
-------
uno dos twa quad    uno dos twa quad

FIRST
-----
uno dos twa quad

…使用此代码

private void button2_Click(object sender,EventArgs e) {
    string[] strArrGroups = new string[3] { "FIRST","SECOND","THIRD" };
    string[] strArrItems = new string[4] { "uno","quad" };
    for (int i = 0; i < strArrGroups.Length; i++)
    {
        listView1.Groups.Add(new ListViewGroup(strArrGroups[i],HorizontalAlignment.Left));
        for (int j = 0; j < strArrItems.Length; j++) {
            ListViewItem lvi = new ListViewItem(strArrItems[j]);
            listView1.Items.Add(lvi);
            lvi.SubItems.Add("Hasta la Vista,Mon Cherri!");
            listView1.Items[j].Group = listView1.Groups[i];
        }
    }
}

UPDATE

如果你问我,ListView的View属性会有点奇闻趣事:

默认的“LargeIcon”设置最初显示(并且SmallIcon具有相同的效果).
“细节”只给我组头标题(没有项目)
“列表”给了我项目(一行一行,我想要),但没有组/标题
“瓷砖”给了我:

Kannst du mich sehen?
---------------------
uno     dos
twa     quad

…使用button1的代码和:

Default
---------------------
uno     dos
twa     quad
uno     dos
twa     quad

FIRST
---------------------
uno     dos
twa     quad

…用button2的代码

或者:

1) I'm stupid
2) ListView is very counterintuitive
-or
3) Nobody ever wants to use the ListView the way I'm trying to use it...if that's the case,should I be using a different control instead?

~~~
侧面(或底部)问题:由于我居住在StackOverflow上,是否有可能成为双重公民,这样做是否有任何税收优惠?

解决方法

这对我有用:
listView1.Columns.Add("Col1");
listView1.Columns.Add("Col2");

string[] strArrGroups = new string[3] { "FIRST","THIRD" };
string[] strArrItems = new string[4] { "uno","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);
    }
}

事实证明,您必须将项目添加到组中,而不是在项目上设置组属性,如其他问题所示.非常非常奇怪.

结果是:

在.Net 4,WinForms,VS2010中测试过

原文链接:https://www.f2er.com/csharp/91889.html

猜你在找的C#相关文章