Reputation: 185
REVISED: I have a Windows Forms Application and have added a ListView. I am able to add items to my list view, but I am wanting to number each row that has an item. I want those numbers to appear in column 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());
}
}
}
Sorry of the change was somewhat dramatic after the revision. I now have the numbers appearing under the Font ID, but now I can't seem to get it to increment. I think I'm very close.
Answer: Here is how I implemented the suggestions by 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
Upvotes: 0
Views: 3358
Reputation: 14153
Old Question:
You need to set the SubItems
on the ListViewItem
you just added.
lvi.Text = fontFileName;
lvi.SubItems.Add(initialID.ToString());
listView1.Items.Add(lvi);
New Question:
Your counter loop will not work because it resets each time, and because your InitialID
is one, i
will always be 0.
I suggest using the following:
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++;
}
}
Upvotes: 1