Search code examples
c#objectlistview

Updating items in a ObjectListView


I am using the ObjectListView control in my application. Every 1 second, I have a timer that ticks, and refreshes a List of type TransferMetrics (List<TransferMetrics> activeTransfers). My TransferMetrics class looks like this;

class TransferMetrics
{
    public Guid guid { get; set; }
    public string jobName {get; set;}
    public int TotalTransferred {get; set;}
    public int TotalToTransfer { get; set; }
    public int TotalFailed { get; set; }
    public DateTime TimeStarted { get; set; }
    public string status { get; set; }

    //Used for single file uploads only
    public double percentage { get; set; }
    public int cps { get; set; }

    //used for database transfers
    public string dbPath { get; set; }
    public bool restoreDatabase { get; set; }
    public string dbName { get; set; }
    public DocsToTransferBundle docsBundle { get; set; }
    public bool databaseRestored {get; set;}
    public bool dbRestoreInProgress { get; set; }

    public List<FailedUploadsBundle> FailedUploadDetails { get; set; }
}

Every 1 second, I want to update the ObjectListView to add any new items that don't exist in the control already, and update those that already do. The unique identifier for each record is the guid property.

In my timer tick method, I am calling the following code; lvTransfers2.SetObjects(activeTransfers);. This works, however it causes the control to "flash", i.e, remove all the items and re-draw them.

What is the elegant way to do what I am trying to achieve? I want any new instances in the List to be added to the control, and any existing items to be updated.

My second attempt was this;

    var at = uploadManager.GetTransferMetrics();

    foreach(var a in at)
    {
        var item = activeTransfers.Where(x => x.guid == a.guid).FirstOrDefault();
        if (item != null)
        {
            lvTransfers2.UpdateObject(item);
            //item = a;
        }
        else
        {
            activeTransfers.Add(a);
        }
    }

Solution

  • you can first bind a list to objectlistview

    if (classes == null) classes = new List<myClass>();
                objectListView1.SetObjects(classes);
                timer1.Interval = 1000;
                timer1.Start();
    

    in your timer's tick event you must add new object to list and build the list:

    private void timer1_Tick(object sender, EventArgs e)
            {
                myClass class1 = new myClass();
                class1.Description = i.ToString();
                classes.Add(class1);
    
                objectListView1.BuildList(true);
    
                ++i;
            }
    

    I'd checked it and its not flashing each time. Hope this helps