Why do I need to remove the current item in my list before adding another one?

So I'm trying something new .. I've added a global ListViewItem at the top of the code, so I can easily add new subitems to the list whenever I see it fits.

So, to try this new method, I made a simple list and a button to add the current time. When I click it as soon as it works fine, but if I try to click add again it throws me this error.

System.ArgumentException: "Unable to add or insert element '11:24' at more than one location. You must first remove it from the current location or clone it. '

Is there a way I can get past this without deleting or cloning?

using System;
using System.Windows.Forms;

namespace Listviews
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        ListViewItem lvi = new ListViewItem();

        private void btnAdd_Click(object sender, EventArgs e)
        {
            string time = DateTime.Now.ToString("HH:mm");
            lvi.Text = time;
            listView1.Items.Add(lvi);
        }
    }
}

      

+3


source to share


2 answers


You add the same element over and over again (different text doesn't mean it's a different element). The method Add

ListView

has an overload that takes a string. This will automatically create a new one listviewitem

.

namespace Listviews
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        // Not needed
        //ListViewItem lvi = new ListViewItem();

        private void btnAdd_Click(object sender, EventArgs e)
        {
            string time = DateTime.Now.ToString("HH:mm");
            // Just add the time directly as a string
            listView1.Items.Add(time);
        }
    }
}

      



Alternatively check the first comment on your question. But as long as you don't want to modify elements or store them externally, you don't need to create listviewitem

.

+3


source


    ListViewItem lvi;
    private void button1_Click(object sender, EventArgs e)
    {
        lvi  = new ListViewItem();
        string time = DateTime.Now.ToString("HH:mm");
        lvi.Text = time;
        listView1.Items.Add(lvi);
    }

      



You can use this.

0


source







All Articles