0
votes

I have two listboxes and I want to add an for each item from listbox1 to listbox2 in order. I mean I want Listbox2 shows the previous item value of the listbox1 item.How can I erase or hide the repetating items as you see in below?

For example;

 Listbox1    Listbox2
     0          -
     1          0
     2          1
     3          2 
     4          3
    ...        ...

This is what I see;My code display

Here is my code;

      using System;
     using System.Collections.Generic;
     using System.ComponentModel;
     using System.Data;
     using System.Drawing;
     using System.Linq;
     using System.Text;
     using System.Threading.Tasks;
     using System.Windows.Forms;

  namespace DistanceExample
{
public partial class Form1 : Form
{
    int i;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        timer1.Enabled = true;
    }

    private void button2_Click(object sender, EventArgs e)
    {
        timer1.Enabled = false;
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        i++;
        foreach (var item in listBox1.Items)
        {
            listBox2.Items.Add(item);
        }
        listBox1.Items.Add(i);


       }
   }
}
1
Just add listBox2.Items.Clear() before foreach() loop. But I have to notice that in this way you will reenter all the values from first listBox to the second on every added itemSamvel Petrosov

1 Answers

1
votes

Just remove the items in listBox2 with the Clear method:

private void timer1_Tick(object sender, EventArgs e)
{
    i++;
    // remove old items
    listBox2.Items.Clear();

    foreach (var item in listBox1.Items)
    {
        listBox2.Items.Add(item);
    }
    listBox1.Items.Add(i);
}