Methodinvoker does not update listbox C#

Asked

Viewed 94 times

0

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

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()));
}

Is updating the textLabel, but does not update the listbox;

  • 2

    This is looking so funny.

  • Why do you update the list every X seconds and not when the list is actually modified? You are using WPF or Windows Forms?

  • How do I update every modification? I’m using Windows Forms

1 answer

1

The listbox notes changes in the object you are passing to the property Datasource, setting the same object does not help, 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 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);
}
  • Do you know if the Bindinglist property is in different project works? I am working with two project, one main project and another that would be the form;

  • 1

    It works yes, you just need the instance of a BindingList and fill with the items you want to display and associate to Datasource, the location of the instance in the project is indifferent. You can pass the parameter to the form if you want.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.