1、实现功能
dataGridVie控件绑定List数据,点击按钮更新List数据并重新绑定,dataGridVie控件的数据更新。
2、编程步骤
(1)、定义Person类
public class Person
{
private string name;
private int age;
private double weight;
public string Name { get { return name; } set { name = value; } }
public int Age { get { return age; } set { age = value; } }
public double Weight { get { return weight; } set { weight = value; } }
public Person(string _name,int _age,double _weight)
{
name = _name;
age = _age;
weight = _weight;
}
}
(2)、初始化dataGridVie控件
dataGridView2.AutoGenerateColumns = false;
dataGridView2.Columns.Add("name", "姓名");
dataGridView2.Columns[0].DataPropertyName = "name";
dataGridView2.Columns.Add("age", "年龄");
dataGridView2.Columns[1].DataPropertyName = "age";
dataGridView2.Columns.Add("weight", "体重");
dataGridView2.Columns[2].DataPropertyName = "weight";
(3)、初始化List数据
List<Person> people;
people = new List<Person>() {
new Person("Alan",16,50.65),
new Person("Bob",18,68.43),
new Person("Charle",16,50.65)
};
(4)、绑定List
dataGridView2.DataSource = new BindingSource(new BindingList<Person>(people), null);
或
dataGridView2.DataSource = new BindingList<Person>(people);
或
dataGridView2.DataSource = people;
(5)、按钮事件处理
private Boolean flag = false;
private void btDataGridTest_Click(object sender, EventArgs e)
{
if (flag)
{
people[0] = new Person("Alan", 16, 50.65);
people[1] = new Person("Bob", 18, 68.43);
people[2] = new Person("Charle", 16, 50.65);
flag = false;
}
else
{
people[0] = new Person("张三", 20, 70.65);
people[1] = new Person("李四", 22, 80.65);
people[2] = new Person("王麻子", 24, 90.65);
flag = true;
}
//dataGridView2.DataSource = new BindingSource(new BindingList<Person>(people), null);
dataGridView2.DataSource = new BindingList<Person>(people);
}
3、实现效果
切换界面1
切换界面2
4、说明
dataGridVie控件绑定List数据,每次数据更新需重新绑定。