winForm 使用List<T> 绑定 DataGridView.DataSource ,无法正常显示

winForm 使用 List<T> 绑定 DataGridView.DataSource ,无法正常显示。

\(\color{red}{如果直接用类的字段等来显示,则无法显示数据,要用类的属性才能正常显示。}\)

这样显示不了。

class Student {
            public string Name;
            public string Age ;
            public string Gender;
        }
        
        private void Button5_Click(object sender, EventArgs e) {
            List<Student> students = new List<Student>();
            Student hat = new Student("Hathaway", "12", "Male");
            Student peter = new Student("Peter", "14", "Male");
            students.Add(hat);
            students.Add(peter);
            this.dataGridView3.DataSource = students;
           }
        }

改成这样,就可以显示了。

class Student {
            private string _Name, _Age, _Gender;
            public string Name{
                get { return _Name; }
                set { _Name = value; }
            }
            public string Age {
                get { return _Age; }
                set { _Age = value; }
            }
            public string Gender {
                get { return _Gender;}
                set { _Gender = value; }
            }   
        }
        
        private void Button5_Click(object sender, EventArgs e) {
            List<Student> students = new List<Student>();
            Student hat = new Student("Hathaway", "12", "Male");
            Student peter = new Student("Peter", "14", "Male");
            students.Add(hat);
            students.Add(peter);
            this.dataGridView3.DataSource = students;
           }
        }
posted @ 2019-12-31 08:54  czc1999  阅读(251)  评论(0编辑  收藏  举报