C# 如何将列表计数绑定到标签
我有一个绑定到列表的DataGridView和一个显示记录数的标签。我遇到了和以前一样的问题。(所以我偷了他的头衔)。网格上的任何添加或删除操作都不会更新标签 基于,我创建了我的自定义列表,继承C# 如何将列表计数绑定到标签,c#,winforms,data-binding,C#,Winforms,Data Binding,我有一个绑定到列表的DataGridView和一个显示记录数的标签。我遇到了和以前一样的问题。(所以我偷了他的头衔)。网格上的任何添加或删除操作都不会更新标签 基于,我创建了我的自定义列表,继承bindingslist并实现INotifyPropertyChanged public class CountList<T> : BindingList<T>, INotifyPropertyChanged { protected override void I
bindingslist
并实现INotifyPropertyChanged
public class CountList<T> : BindingList<T>, INotifyPropertyChanged
{
protected override void InsertItem(int index, T item)
{
base.InsertItem(index, item);
OnPropertyChanged("Count");
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
OnPropertyChanged("Count");
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
如有任何建议,将不胜感激。谢谢。事实上,这比你想象的要简单得多 Microsoft已经创建了BindingSource控件,因此,您需要使用它,然后处理BindingSource事件以更新标签:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
private BindingSource source = new BindingSource();
private void Form1_Load(object sender, EventArgs e)
{
var items = new List<Person>();
items.Add(new Person() { Id = 1, Name = "Gabriel" });
items.Add(new Person() { Id = 2, Name = "John" });
items.Add(new Person() { Id = 3, Name = "Mike" });
source.DataSource = items;
gridControl.DataSource = source;
source.ListChanged += source_ListChanged;
}
void source_ListChanged(object sender, ListChangedEventArgs e)
{
label1.Text = String.Format("{0} items", source.List.Count);
}
公共类人物
{
公共int Id{get;set;}
公共字符串名称{get;set;}
}
private BindingSource=new BindingSource();
私有void Form1\u加载(对象发送方、事件参数e)
{
var items=新列表();
添加(newperson(){Id=1,Name=“Gabriel”});
添加(newperson(){Id=2,Name=“John”});
添加(newperson(){Id=3,Name=“Mike”});
source.DataSource=项目;
gridControl.DataSource=source;
source.ListChanged+=source\u ListChanged;
}
无效源\u ListChanged(对象发送方,ListChangedEventArgs e)
{
label1.Text=String.Format(“{0}项”,source.List.Count);
}
虽然我更喜欢修复自定义列表,但BindingSource已经足够酷了。thx:>是的,我认为CountList是一个很酷的概念,但我更希望它能用于研究概念,以了解整体模式和其他东西,我说我们必须始终使用更简单的模型(如果它是一个好的模型),而不是试图重新发明轮子。:)我发现自己创建了很多这样的类,但只使用了少数,哈哈!
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
private BindingSource source = new BindingSource();
private void Form1_Load(object sender, EventArgs e)
{
var items = new List<Person>();
items.Add(new Person() { Id = 1, Name = "Gabriel" });
items.Add(new Person() { Id = 2, Name = "John" });
items.Add(new Person() { Id = 3, Name = "Mike" });
source.DataSource = items;
gridControl.DataSource = source;
source.ListChanged += source_ListChanged;
}
void source_ListChanged(object sender, ListChangedEventArgs e)
{
label1.Text = String.Format("{0} items", source.List.Count);
}