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);
}
}
}
source to share
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
.
source to share