How to update a datagridview automatically?

Asked

Viewed 4,952 times

6

I created an application that will display the data of a particular view in a control datagridview. The entire application is already ready: the data upload, the update button and also the events load and activated.

Technologies used:

  • ADO.NET Entity Data Model
  • EF 6.x Entityobject Generator
  • SQL Server 2012

Note: I am using Bindingsource in the datagridview Datasource property to load the information.

Below is the code of my application:

private void frmDados_Load(object sender, EventArgs e)
{
    CarregaDados();
}

private void CarregaDados()
{
    using (var context = new DadosEntities())
    {
        vGRUPOSBindingSource.DataSource = context.VGRUPOS.ToList();
    }
}

private void btnAtualizar_Click(object sender, EventArgs e)
{
    CarregaDados();
}

/// <summary>
/// Evento acionado quando o foco retornar ao formulário
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void frmDados_Activated(object sender, EventArgs e)
{
    CarregaDados();
}

My doubt

How to update control datagridview automatically after any changes in table data?

Whether directed by the database or another open application being powered by other users.

The control needs to be updated without any user influence - by activating the focus on the application or by clicking the Update button.

Sample scenario

With my open application, defined as a information panel the information on the stock of products is displayed. As per another app a stock control (in Winform, Mobile or WEB), gives entrances or exits, my dashboard app needs to show new information.

It can happen also of a batch operation, update the stock of many products via database, ie a update directly by SQL, therefore, my information dashboard needs to update in real time the information on datagridview.

  • Winform or WPF? Know Databinding?

  • I am using winform. Databinding already used in wpf.

1 answer

1

With Bindinglist (System.ComponentModel.BindingList) i got this effect of updating a data and then updating Datagridview. The only annoying thing is having to add the new item in Bindinglist to have the effect, it is not so automatic, but, it frees me from carrying the data again from the database to Datagridview.

Create a ViewModel as in the code just below, implementing the interface Inotifypropertychanged:

public class PessoaViewModel: INotifyPropertyChanged
{
    private int _id;
    private string _nome;

    public int Id {
        get
        {
            return _id;
        }
        set
        {
            if (_id != value)
            {
                _id = value;
                OnPropertyChanged(new PropertyChangedEventArgs("Id"));
            }
        }
    }
    public string Nome
    {
        get
        {
            return _nome;
        }
        set
        {
            if (_nome != value)
            {
                _nome = value;
                OnPropertyChanged(new PropertyChangedEventArgs("Nome"));
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, e);
        }
    }
}

In the form create a property:

protected BindingList<PessoaViewModel> PessoasBindingList;

and in the Load Form make your load:

PessoasBindingList = new BindingList<PessoaViewModel>(
    Database.Pessoas.Select(c => new PessoaViewModel
{
    Id = c.Id,
    Nome = c.Nome
}).ToList());

DataGridViewPessoas.DataSource = PessoasBindingList;
DataGridViewPessoas.Update();
DataGridViewPessoas.Refresh();
Update();

When you include an item in your database, you should also include it in the created property PessoasBindingList

Example:

Insert

Pessoa p = new Pessoa();
p.Nome = TxtNome.Text;
Database.Pessoas.Add(p);
Database.SaveChanges();
PessoasBindingList.Add(new PessoaViewModel()
{
    Id = p.Id,
    Nome = p.Nome
});

Update

int Id = int.Parse(TxtId.Text);
Pessoa p = Database.Pessoas.Find(Id);
p.Nome = TxtNome.Text;
Database.Entry(p).State = System.Data.Entity.EntityState.Modified;
Database.SaveChanges();
PessoasBindingList
    .Where(c => c.Id == Id)
    .FirstOrDefault()
    .Nome = TxtNome.Text;

If it is excluded it is likewise excluded from the base and after the Bindinglist.

  • 1

    John, thank you for the reply, however, after the implementation of this technique, I will be in the same situation: Datagridview is not updated automatically until again I search the new information from the bank. Include in my question an example scenario.

  • @But now I understand your logical development process, really this solution would work if the same variable had access to other screens, and so it would work the way you asked. But, you could then use WPF on that screen so it’s the only practical way to do something like this. It could also create a timer from time to time updated this screen, also work with that base you already have. Really WPF is the viable solution, IE, Windows Forms for this really does not give the expected effect !!! Just a hint on new questions, always put the scenario this helps and a lot!

  • @Although this solution does not suit you, it is works if you use on the same screen the same variables... Binding happens

  • 1

    Yes John, in the same window yes.

Browser other questions tagged

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