1 回答
TA贡献1827条经验 获得超4个赞
正如评论中所述,将BindingList(或 DataTable)与BindingSource关联起来可以带来一些有趣的好处。
当修改其中一个元素BindingList
或将新元素添加到列表中时,所有绑定控件都会自动更新。
您可以使用MovePrevious()
、MoveNext()
、MoveFirst()
、MoveLast()
方法来导航 中的元素BindingList
(还可以使用其他有用的方法和事件,请参阅有关 BindingSource 功能的文档)。
这里,a BindingList<T>
(其中T
是Member
下面所示的类)被设置为BindingSource的DataSource。两者都是Form类的Fields,可以根据需要修改。
然后将 BindingSource 用作 ListBox 的 DataSource。
Text
然后,使用 BindingSource 将两个 TextBox 控件的属性绑定到该类的属性之一Member
。这样,Text 属性就设置为 BindingList 的当前 Item。所有控件都是同步的:
txtMemberName.DataBindings.Add(new Binding("Text", membersSource, "FirstName", false, DataSourceUpdateMode.OnPropertyChanged)); txtMemberLastName.DataBindings.Add(new Binding("Text", membersSource, "LastName", false, DataSourceUpdateMode.OnPropertyChanged));
在实践中,它是这样工作的:
https://i.stack.imgur.com/sIlxa.gif
请注意,当修改 TextBox 的 Text 时,ListBox 的当前 Item 会实时更新。
BindingList<Member> members = null;
BindingSource membersSource = null;
public partial class frmMembers : Form
{
public frmMembers() {
InitializeComponent();
InitializeDataBinding();
}
private void InitializeDataBinding()
{
members = new BindingList<Member>();
membersSource = new BindingSource(members, null);
lstBoxMembers.DataSource = membersSource;
txtMemberName.DataBindings.Add(new Binding("Text", membersSource,
"FirstName", false, DataSourceUpdateMode.OnPropertyChanged));
txtMemberLastName.DataBindings.Add(new Binding("Text", membersSource,
"LastName", false, DataSourceUpdateMode.OnPropertyChanged));
}
private void btnAddMember_Click(object sender, EventArgs e)
{
var frmNew = new frmNewMember();
if (frmNew.ShowDialog() == DialogResult.OK && frmNew.newMember != null) {
members.Add(frmNew.newMember);
}
}
private void btnMovePrevious_Click(object sender, EventArgs e)
{
if (membersSource.Position > 0) {
membersSource.MovePrevious();
}
else {
membersSource.MoveLast();
}
}
private void btnMoveNext_Click(object sender, EventArgs e)
{
if (membersSource.Position == membersSource.List.Count - 1) {
membersSource.MoveFirst();
}
else {
membersSource.MoveNext();
}
}
}
新会员表格样本:
public partial class frmNewMember : Form
{
public Member newMember;
private void btnSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtMemberName.Text) ||
string.IsNullOrEmpty(txtMemberLastName.Text)) return;
newMember = new Member(txtMemberName.Text, txtMemberLastName.Text);
}
}
会员类别示例:
[Serializable()]
public class Member
{
public Member() { }
public Member(string firstName, string lastName)
{
this.FirstName = firstName;
this.LastName = lastName;
}
public string FirstName { get; set; }
public string LastName { get; set; }
public override string ToString() => $"{this.FirstName} {this.LastName}";
}
- 1 回答
- 0 关注
- 97 浏览
添加回答
举报