MethodInvoker does not update listBox C #

0

How to implement a timer that every cycle updates a listbox in C #;

Method to create the timer:

private void CriaTimer()
{
    System.Timers.Timer aTimer = new System.Timers.Timer();
    aTimer.Elapsed += OnTimedEvent;
    aTimer.Interval = 100;
    aTimer.Enabled = true;
}

private void OnTimedEvent(object sender, ElapsedEventArgs e)
{
    AtualizaControlesForm();
}

Method to update components:

public void AtualizaControlesForm()
{
   Invoke(new MethodInvoker(() => this.lblPorcentagemGeracao.Text = UtilidadesGeraSped.valorProgressoGeracao + "%"));
   Invoke(new MethodInvoker(() => this.listBoxInformacoesLog.DataSource = Mensagens.logErroseInfo));
   Invoke(new MethodInvoker(() => this.listBoxInformacoesLog.Refresh()));
}

You are updating textLabel, but it does not update the listBox;

    
asked by anonymous 13.09.2017 / 22:41

1 answer

1

listbox observes changes in the object you are passing to the Datasource property, getting set to the same object does not work, the object itself has to be modified.

One solution is to use the class BindingList , every time an item is added to it, the listbox will be automatically informed:

BindingList is a class of the namespace System.ComponentModel .

Example:

// TipoDoDado é o tipo do item que vai no seu listbox, 
// no seu caso é o item dentro da lista logErroseInfo.
static BindingList<TipoDoDado> data = new BindingList<TipoDoDado>();

MeuConstrutor()
{
    this.listBoxInformacoesLog.Datasource = data;
}

private void CriaTimer()
{
    System.Timers.Timer aTimer = new System.Timers.Timer();
    aTimer.Elapsed += OnTimedEvent;
    aTimer.Interval = 100;
    aTimer.Enabled = true;
}

private void OnTimedEvent(object sender, ElapsedEventArgs e)
{
    AtualizaControlesForm();
}

public void AtualizaControlesForm()
{
   Invoke(new MethodInvoker(() => this.lblPorcentagemGeracao.Text = UtilidadesGeraSped.valorProgressoGeracao + "%"));

   // Adicione aqui novos itens a lista 
   // Ex.: data.Add(novoItem);
}
    
14.09.2017 / 15:39