0

I have a GridView that is being populated by a subset .Select of Tables as below; then bound the list to the Grid View Data source.

However, I found myself calling LoadCandidates() many times! any time a record is changed or even when adding a new record, in order to refresh the Data Grid View. This means I have to query the database and then append it to the DGV Data Source every time a change happens, to maintain the below DGV headers (subset).

is there a better way of implementing this?

private async Task LoadCandidates()
{
            var candiatesList = await _dbContext.Candidates
            .Include(i => i.Candimmigration)
            .Select(s => new
            {
                Id = s.Id,
                FirstName = s.FirstName,
                LastName = s.LastName,
                DateOfBirth = s.DateOfBirth,
                VisaNo = s.Candimmigration.VisaNo,
                PassportNo = s.Candimmigration.PassportNo,
            })
            .ToListAsync();
            dgv.DataSource = candiatesList;
}

UPDATE:

Managed to get the first part done, however, I am not sure how to only display the above fields in my gridview rather than showing the entire candidate properties

    _dbContext.Candidates.Load();
    dgvCandidates.DataSource = _dbContext.Candidates.Local.ToBindingList();
// only display the columns above (Id, FirstName, LastName, etc..) 
Unis
  • 365
  • 1
  • 4
  • 13

1 Answers1

0

I believe you might want to implement Reactive behavior to your GridView. This is achieved by Binding a UI element like your GridView to an Observable variable. Once you've made this binding, the grid will update itself every time the variable is set. There are many ways to do this and even frameworks that facilitate it.

Here is a good example of how to achieve this with regular .Net:

https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/how-to-create-and-bind-to-an-observablecollection?view=netframeworkdesktop-4.8

Slack Groverglow
  • 846
  • 7
  • 25
  • I believe the Observable Variable does not work with WinForm controls. https://stackoverflow.com/questions/12015576/binding-observablecollection-to-datagridview – Unis Sep 03 '22 at 07:07