码迷,mamicode.com
首页 > Windows程序 > 详细

DataGridView绑定DataTable的正确姿势

时间:2019-08-06 14:09:04      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:data   rem   save   datagrid   span   com   ini   datatable   例程   

1. 将DataTable 绑定到BindingSource

2. 将BindingSource绑定到DataGridView

3. DataGridView修改完要从Datatable取值时,同步过去时,BindingSource和DataGridView两个都要执行EndEdit()

例程:

 public partial class Form1 : Form
    {
        DataTable mTable = new DataTable();
        BindingSource mbs = new BindingSource();
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            mTable.Columns.Add("Name",typeof(string));
            mTable.Columns.Add("Age", typeof(float));
            mTable.Columns.Add("Dept", typeof(string));
            mTable.Columns.Add("IsDeleted", typeof(bool));
            mTable.Rows.Add("Jack", 21, "C1", false);
            mTable.Rows.Add("Rose", 21, "C2", false);
            mTable.Rows.Add("Tom", 21, "C1", false);
            mTable.Rows.Add("Micky", 21, "C1", false);
            mTable.Rows.Add("Steven Chou", 21, "C1", false);
            mbs.DataSource = mTable;
            grd.DataSource = mbs;
        }

        private void BtnDel_Click(object sender, EventArgs e)
        {
            mTable.Rows.Remove(mTable.Rows[grd.CurrentRow.Index]);
        }

        private void BtnSave_Click(object sender, EventArgs e)
        {
            grd.EndEdit();
            mbs.EndEdit();

            int N = mTable.Rows.Count;
            
        }
    }

 

DataGridView绑定DataTable的正确姿势

标签:data   rem   save   datagrid   span   com   ini   datatable   例程   

原文地址:https://www.cnblogs.com/ccjungle/p/11308195.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!