1. 程式人生 > 其它 >如何實現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++;
        }
    }