我正在尝试让Winforms组合框在新行写入数据库时自动刷新。
POCO EF课程:
public class BaseSweep
{
public int BaseSweepId { get; set; }
//stuff removed for clarity
}
我通过像这样的BindingList绑定数据:
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";
}
这适用于初始绑定,显示表中的当前ID。随着新行添加到表中,LocalDbContext.BaseSweep.Local
中的计数会按预期上升。但是,comboBoxSweepIds
永远不会更新。我有什么想法吗?
答案 0 :(得分:0)
您需要触发事件并在每次添加行时调用bind。
答案 1 :(得分:0)
Mark W以正确的方式领导我:
//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;
}
在表单类(BindingList<T>
)
_sweepCollection
在第一个数据绑定中,设置事件处理程序:
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";
}
}