How to update a datagridview automatically?

6

I've created an application that will display the data of a given view in a datagridview control. The whole application is ready: loading the data, the button to update 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 the BindingSource in the DataSource property of the datagridview to load the information.

Here is the code for 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 question

How do I update the datagridview control automatically after any changes to the table data?

Be directed by the database or by another open application being fed by other users.

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

Sample scenario

With my open application, defined as an dashboard , the product stock information is displayed. As another application a stock control (in WinForm, Mobile or WEB) gives inputs or outputs, my dashboard app needs to show the new information.

It can also happen from a batch operation, updating the stock of many products via the database, that is, a update directly by SQL , so my dashboard needs to update the information in real time no datagridview .

    
asked by anonymous 24.05.2016 / 22:24

1 answer

1

With BindingList ( System.ComponentModel.BindingList ) I got this effect of updating a data and then updating the DataGridView. The only annoying thing is having to add the new item in the BindingList to have the effect, it is not so automatic, but, this frees me from getting load the data back from the database to DataGridView .

Create a ViewModel as in the code below by 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 of the Form load it:

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

How much do you include an item in your database, you should also include 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 you're deleting it's the same way it deletes from the base and then the BindingList .

    
25.05.2016 / 02:48