其他分享
首页 > 其他分享> > 如何实现DataGridView绑定List<T>实时更新(DataGridView绑定DataTable默认实时更新)

如何实现DataGridView绑定List<T>实时更新(DataGridView绑定DataTable默认实时更新)

作者:互联网

需要使用 BindingList , BindingList  实现了IRaiseItemChangedEvents 接口,通知客户端属性更改。

并且绑定的Entity 也要实现 INotifyPropertyChanged ,通知客户端实体属性更改

然后dataGridView 就能实现随 Lis实时刷新,WPF 的MVVM 也是依靠INotifyPropertyChanged  实现的。

public partial class Form2 : Form
    {
        BindingList<Student> students;
        public Form2()
        {
            InitializeComponent();
            dataGridView1.RowHeadersVisible = false;
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.AllowUserToAddRows = false;
            students= new BindingList<Student>();
            students.Add(new Student { Name = "张三", Age = "18" });
            students.Add(new Student { Name = "李四", Age = "18" });
            this.bindingSource1.DataSource = students;
            this.dataGridView1.DataSource =this.students;
        }
        public  class Student: BindableBase
        {
            private string name = string.Empty;
            private string age = string.Empty;
            public string Name { get=>name;set=> SetProperty(ref name,value); }
            public string Age { get => age; set => SetProperty(ref age, value); }
        }
        public abstract class BindableBase : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;
            protected bool SetProperty<T>(ref T field, T newValue, [CallerMemberName] string propertyName = null)
            {
                if (!EqualityComparer<T>.Default.Equals(field, newValue))
                {
                    field = newValue;
                    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
                    return true;
                }
                return false;
            }
        }
        int no = 1;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            students.Add(new Student { Name="王二麻"+no,Age="88"});
            no++;
        }
    }

  

 

标签:string,students,Age,绑定,实时,DataGridView,dataGridView1,new,public
来源: https://www.cnblogs.com/zhangshaofeng-wuhe/p/16095350.html