C#中DataGridView绑定数据源,实现数据源更新,界面和被绑定的数据同时更新
要点:
1、使用BindingSource与控件DataDataSource绑定,而不是直接使用数据源
2、更新BindingSource而不是更新自己的数据源
public class Record { public string _ID { set; get; } public string _Name { set; get; } public int _Age { set; get; } }
public partial class Form1 : Form { //使用BindingSource与控件DataDataSource绑定,而不是直接使用数据源 public BindingSource source = new BindingSource(); public Form1() { InitializeComponent(); List<Record> records = new List<Record>() { new Record() {_ID="A001",_Name="张三",_Age=1}, new Record() { _ID = "A002", _Name = "李四", _Age = 2 } , new Record() { _ID = "A003", _Name = "王五", _Age = 3 } }; source.DataSource = records; } private void Form1_Load(object sender, EventArgs e) { this.dataGridView1.DataSource = source; } private void button1_Click(object sender, EventArgs e) { //更新BindingSource而不是更新自己的数据源 source.Add(new Record() { _ID = "as", _Name = "sjaf", _Age = 12 }); foreach (Record record in source) { Console.WriteLine(record._ID + "|" + record._Name + "|" + record._Age); } } private void button2_Click(object sender, EventArgs e) { this.dataGridView1.Rows.RemoveAt(0); } }