2
votes

I'm new to Databinding in .NET and I want to bind my DataGridView to a object list. This grid may populate in two ways.

There are TextBoxes in the form and users can enter text and when they press Add button a new object is instantiated with the provided fields and it is added to the list.

Other way is, when a user searches for objects, matching objects are loaded from database to the list. Also after searching users should be able to add new items to this list as in the first method.

Finally this list is binded to the DataGridView and now user could do any changes to the items shown in the grid and if it's all right, user could save them.

So in my presenter I have three methods for above requirements.

Class AttendancePresenter 
{
    private void AddAttendance()
    {
        AttendanceList.Add(attendanceModel);
        var bindingList = new BindingList<IAttendance>(AttendanceList);
        var source = new BindingSource(bindingList, null);
        _View.AttendanceGrid = source;
    }


    private void GetAttendance()
    {
        AttendanceList = _DataService.GetAttendance();
        var bindingList = new BindingList<IAttendance>(AttendanceList);
        var source = new BindingSource(bindingList, null);
        _View.AttendanceInGrid = source;
    }

    private void Save()
    {
        _DataService.InsertAttendance (AttendanceList);
    }

}
  1. I'm not sure the way I've binded things is right. And also I wonder if I could use a single binding list here as I'm binding same list to the same DataGridView! Is it possible?

  2. Whats the difference of using BindingSource along and with a BindingList, in this context?

1
Fwiw I'm using an older MVP framework but what I typically see is the View binding to the Presenter, rather than the Presenter setting the views datasource.Eric Scherrer

1 Answers

2
votes

Bind the DataGridView to the presenters AttendanceList right in the constructor, assuming your view is instantiated at that point. Then in the presenter do something like this:

Class AttendancePresenter 
{
    private readonly BindingList<IAttendance> _attendanceList;

    public AttendancePresenter()
    {
        _attendanceList = new BindingList<IAttendance>();
        _View.AttendanceGrid = _attendanceList;
    }

    private void AddAttendance()
    {
        _attendanceList.Add(attendanceModel);
    }

    private void GetAttendance()
    {
        _attendanceList.Clear();

        var attendance = _DataService.GetAttendance();

        foreach (var attendant in attendance)
        {
            _attendanceList.Add(attendant);
        }
    }

    private void Save()
    {
        _DataService.InsertAttendance (_attendanceList);
    }
}