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);
        }
    }
复制代码

 

posted @   百年一梦  阅读(7337)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App
点击右上角即可分享
微信分享提示