Error trying to insert dynamically in lists of c # (You can not add or insert elements in more than one site)

2

Well now I want to fill a listview with information from my Database, but I get the following error:

  

Can not add or insert item in more than one site. You must first   remove it from its current location or clone it.

Current Code:

    while (reader.Read())
    {
        lvi.Text = reader.GetString("Articulo");
        lvi.SubItems.Add(reader.GetString("Costo"));
        lvi.SubItems.Add(reader.GetString("Importancia"));
        lstData.Items.Add(lvi);
    }
    connection.Close();

The first record if it executes correctly but then in the second is when I get this error.

List Code:

        lstData.View = View.Details;

        lstData.Columns.Add("Nombre");
        lstData.Columns.Add("Precio");
        lstData.Columns.Add("Importancia");
        lstData.Columns[2].Width=110;
        ListViewItem lvi = new ListViewItem();
    
asked by David 08.04.2017 в 00:28
source

1 answer

2

After this line:

lstData.Items.Add(lvi);

Place:

lvi = new ListViewItem();

Your modified code would look like this:

while (reader.Read())
{
    lvi.Text = reader.GetString("Articulo");
    lvi.SubItems.Add(reader.GetString("Costo"));
    lvi.SubItems.Add(reader.GetString("Importancia"));
    lstData.Items.Add(lvi);

    // Limpia la variable para poderla usar al iniciar el ciclo.
    lvi = new ListViewItem();
}
connection.Close();

The error occurs because you are using the variable lvi without having cleaned it from the previous data.

    
answered by 08.04.2017 / 01:00
source