我使用 BindingSource 将我的 NHibernate 对象绑定到 DataGridView,我想要的是对象与数据库紧密连接,即如果对象发生某些变化,则更改应该在 Commit(用户按下保存按钮)或 RollBack 后影响数据库否则交易(取消按钮)。但也存在一些问题: 1. 如果事务回滚,对象不会被回滚。2.如何监控对象列表的变化。使用 BindingSource 事件会破坏我的模型,甚至无法删除数据库中的对象,因为删除列表项后会调用 BindingSource 更改事件。伙计们,我真的不知道如何实现这样的模型,如果你在这个范围内有经验,请给我一些建议。
班级
class AudienceFormController
{
private AudiencesForm _form;
private IList<AudienceType> _audiences;
private BindingSource _bindingSource;
private void BindTable()
{
_audiences = Controller.Manager.RetrieveAll<AudienceType>(SessionAction.Begin);
_bindingSource = new BindingSource();
_bindingSource.DataSource = _audiences;
_bindingSource.AllowNew = true;
_form.AudienceTypesDataGridView.DataSource = _bindingSource;
_form.AudienceTypesDataGridView.AllowUserToAddRows = true;
_form.AudienceTypesDataGridView.AutoGenerateColumns = true;
_form.SaveATypeButton.Click += new EventHandler(SaveATypeButton_Click);
_form.CancelATypeButton.Click += new EventHandler(CancelATypeButton_Click);
_bindingSource.ListChanged += new System.ComponentModel.ListChangedEventHandler(_bindingSource_ListChanged);
}
void _bindingSource_ListChanged(object sender, System.ComponentModel.ListChangedEventArgs e)
{
switch (e.ListChangedType)
{
case ListChangedType.ItemChanged:
{
Controller.Manager.Save(_bindingSource.List[e.NewIndex]);
break;
}
//case ListChangedType.ItemDeleted:
// {
// Controller.Manager.Save(_bindingSource.List[e.OldIndex]);
// break;
// }
}
}
void CancelATypeButton_Click(object sender, EventArgs e)
{
Controller.Manager.RollBack();
_bindingSource.DataSource = Controller.Manager.RetrieveAll<AudienceType>(SessionAction.Begin);
}
void SaveATypeButton_Click(object sender, EventArgs e)
{;
Controller.Manager.Commit();
}
public AudienceFormController(AudiencesForm form)
{
_form = form;
BindTable();
}
}