I'm trying to get a Winforms combobox to automatically refresh when new rows are written to our database.
POCO EF class:
public class BaseSweep
{
public int BaseSweepId { get; set; }
//stuff removed for clarity
}
I'm binding to the data through a BindingList like this:
public BindingList<BaseSweep> TopSweeps()
{
LocalDbContext.BaseSweep.Load();
return LocalDbContext.BaseSweep.Local.ToBindingList();
}
private void BindSweepList() //called in Form_Load
{
comboBoxSweepIds.DataSource = _dataAccess.TopSweeps();
comboBoxSweepIds.DisplayMember = "BaseSweepId";
comboBoxSweepIds.ValueMember = "BaseSweepId";
}
This works fine for the initial binding, shows the current Ids in the table. As new rows are added to the table, the count in LocalDbContext.BaseSweep.Local
goes up as expected. However, comboBoxSweepIds
never u开发者_Go百科pdates. Any ideas what I am doing wrong?
You need to fire an event and call bind each time a row is added.
Mark W led me the right way:
//put an event handler on the collection
public void CollectionChanged<T>(System.Collections.Specialized.NotifyCollectionChangedEventHandler eventHandler) where T : class
{
LocalDbContext.Set<T>().Local.CollectionChanged += eventHandler;
}
Use a private BindingList<T>
in the form class (_sweepCollection
)
On the first databind, set up the event handler:
private void BindSweepList()
{
_sweepCollection = _dataAccess.TopSweeps();
_dataAccess.CollectionChanged<CableSweepDebug>(new System.Collections.Specialized.NotifyCollectionChangedEventHandler(Local_CollectionChanged));
UpdateSweepsData();
}
private void Local_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
UpdateSweepsData();
}
private void UpdateSweepsData()
{
if (comboBoxSweepIds.InvokeRequired)
{
Invoke(new UpdateSweepCount(UpdateSweepsData));
}
else
{
var tmpBind = _sweepCollection.OrderByDescending(t => t.BaseSweepId).Take(100);
comboBoxSweepIds.DataSource = null;
comboBoxSweepIds.DataSource = tmpBind.ToList() ;
comboBoxSweepIds.DisplayMember = "BaseSweepId";
comboBoxSweepIds.ValueMember = "BaseSweepId";
}
}
精彩评论