Binding a List to Repeater in WinForm application

2019-06-04 00:54发布

问题:

I recently started this question. The suggested approach was to use a DataRepeater.

I've seen a lot of examples on how to bind the repeater, but all of them were for ASP, not Windows Form applications.

I have added Label, PictureBox and Button components to the template, but I've not been able to successfully bind my IList<SomeObject> to my DataRepeater.

I'd like to populate those components with information from a list.

How to bind a IList<SomeObject> to a DatarRepeater in WinForm applications?

回答1:

Finally got it working! For future reference, this is what I used:

First call this method to initilize manual binding, using a BindingSource:

private BindingSource bindingSource ;
private void InitUserListArea()
{
    _bindingSource = new BindingSource();
    _bindingSource.DataSource = tempUsers;
    _labelUserListRoleValue.DataBindings.Add("Text", _bindingSource, "Role");
    _labelUserListNameValue.DataBindings.Add("Text", _bindingSource, "Name");
    _labelUserListLastAccessValue.DataBindings.Add("Text", _bindingSource, "LastAccess");
    _dataRepeaterUserList.DataSource = _bindingSource;
}

Then get data (in my case from a webservice) and fill the list with data. After the list is populated, or when any changes occurr:

private void RefreshDataRepeater()
{
    if (_dataRepeaterUserList.InvokeRequired)
    {
        _dataRepeaterUserList.Invoke((Action)(() => { RefreshDataRepeater(); }));
        return;
    }

    _bindingSource.DataSource = null;
    _bindingSource.DataSource = tempUsers;
    _dataRepeaterUserList.DataSource = null;
    _dataRepeaterUserList.DataSource = _bindingSource;
    _dataRepeaterUserList.Refresh();
}