为ListView(C#)中的每一行编号

时间:2014-07-11 02:09:31

标签: c# listview

修订:我有一个Windows窗体应用程序,并添加了一个ListView。我能够将项目添加到列表视图中,但我想为每个有项目的行编号。我希望这些数字出现在第2栏。

        if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            int initialID = 2;

            //Change button text.
            button4.Text = ("Clear/Add Fonts");

            //For each string in the open file dialog array.
            foreach (string fontFileName in ofd.SafeFileNames)
            {
                //Add a line in the list view for each selected file. Don't allow for the same file to appear twice.
                if (listView1.FindItemWithText(fontFileName) == null)
                {
                    for (int i = 0; i < initialID; i++)
                        listView1.Items.Add(fontFileName).SubItems.Add((i).ToString());
                }
            }
        }

enter image description here

对不起,修改后的变化有些引人注目。我现在有数字出现在字体ID下,但现在我似乎无法让它增加。我觉得我非常接近。

答案: 以下是我如何实施Cyral的建议:

if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                int initialID = 1;
                int count = initialID;

                //Change button text.
                button4.Text = ("Clear/Add Fonts");

                //For each string in the open file dialog array.
                foreach (string fontFileName in ofd.SafeFileNames)
                {
                    //Add a line in the list view for each selected file. Don't allow for the same file to appear twice.
                    if (listView1.FindItemWithText(fontFileName) == null)
                    {
                            listView1.Items.Add(fontFileName).SubItems.Add(count++.ToString());
                    }
                }
            }
            else

1 个答案:

答案 0 :(得分:1)

旧问题:

您需要在刚刚添加的SubItems上设置ListViewItem

lvi.Text = fontFileName;
lvi.SubItems.Add(initialID.ToString());
listView1.Items.Add(lvi);

新问题:

您的计数器循环无效,因为它每次都会重置,并且因为InitialID为1,i将始终为0。

我建议使用以下内容:

int initialID = 1; //Make a constant and put it somewhere
int count = initialID; //Will count how many items are added (Could also be done with a for loop with a condition)
foreach (string fontFileName in ofd.SafeFileNames)
{
    //Add a line in the list view for each selected file. Don't allow for the same file to appear twice.
    if (listView1.FindItemWithText(fontFileName) == null)
    {
        ListViewItem lvi = new ListViewItem(fontFileName);
        lvi.SubItems.Add(i.ToString());
        listView1.Items.Add(lvi);
        count++;
    }
}