1

I tried to create a function that creates a ListViewItem and put it in my ListView, but when I use it the second time it just overwrites the first item.

This is the function:

ListViewItem lvi = new ListViewItem(taskName2);
lvi.SubItems.Add(DateTime2);
lvi.SubItems.Add(More2);
listView1.Items.Add(lvi);

How can I do it without overwriting the first item? Is there is a array of ListViewItem or something?

2
  • 1
    Can you show how this is being used? Commented Sep 19, 2015 at 20:33
  • its simple call ` public Form1(string taskName1,string DateTime1,string More1,bool startworkign) { InitializeComponent(); taskName2 = taskName1; DateTime2 = DateTime1; More2 = More1; if(startworkign) { StartWorking(); } }` its called every time the form started Commented Sep 19, 2015 at 21:13

1 Answer 1

1

You need to create a new, separate object for each item in the list, you are adding a pointer to the same object. For example, if you put that whole block in a for loop it should work.

List<ListViewItem> listViewItemHandles = new List<ListViewItem>();
for(int i = 0; i < 10; i++)
{
    ListViewItem lvi = new ListViewItem(taskName2);
    lvi.SubItems.Add(DateTime2);
    lvi.SubItems.Add(More2);
    listView1.Items.Add(lvi);

    listViewItemHandles.Add(lvi);
}
Sign up to request clarification or add additional context in comments.

7 Comments

yes I know I have a counter for my items but I don't know how to add a pointer to the item name to create a separate object. something like: ListViewItem lvi + counter = new ListViewItem(taskName2) I know I should do that but how? how I can add my count to the name of the item?.
I don't fully understand why you need a count. If you want handles to the items, store the objects you create in an array.
I made an example with a List<T> since it is more flexible and probably better for your purposes.
you don't understand me sorry.I meant that every time the function works the function create a new item and put it in the listview but in the second time the function works he overwrite the item that created and made in the first time. I don't want to create multiple items in one function work. I just want to create a new item every time the function works
Then put the code block in a function, it should work.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.