Search code examples
c#winformsbackgroundworkerlistboxitem

How to replace previous item of listbox with next item using backgroundworker c#?


I am adding items to the listbox using backgroundworker. It is showing all the items present in the list one by one after some interval of time. I want to show only current item in the list and not all the items.

This is what I have tried.

 private void backgroundWorker3_DoWork(object sender, DoWorkEventArgs e)
    {

        List<string> result = new List<string>();

        var found = obj.getFiles();//List<strings>
        if (found.Count != 0)
        {

            for (int i = 0; i < found.Count; i++)
            {
                int progress = (int)(((float)(i + 1) / found.Count) * 100);
                if (found[i].Contains("SFTP"))
                {
                    result.Add(found[i]);

                    (sender as BackgroundWorker).ReportProgress(progress, found[i]);
                }
                System.Threading.Thread.Sleep(500);
            }



            e.Result = result;

        }
    }

    private void backgroundWorker3_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        if (e.UserState != null)

        listBox3.Items.Add(e.UserState);

    }

Solution

  • I want to show only current item in the list and not all the items.

    Although this is a bit of a hack, I think it should work for what you describe:

    // just call clear first
    listBox3.Items.Clear();
    listBox3.Items.Add(e.UserState);
    

    Truth be told, are you sure you want a ListBox in this circumstance? After all, it's not really a list, it's only an item.