optimize updates to DataTable bound to DataGridView

后端 未结 7 1229
执念已碎
执念已碎 2021-02-14 19:27

I have a Form in my application that displays some data. When I first show the Form, I load some data into a DataTable then bind the DataTable to a DataGridView. I also start an

7条回答
  •  一向
    一向 (楼主)
    2021-02-14 20:08

    You can try using the Merge method on the DataTable. I'll try to create a simple demo app and post it here, but the idea is simple. When you want to update the Grid, query the results into a new DataTable, and then merge the old table with the new table. As long as both tables have primary keys (you can create them them im memory if they don't come back from the DB) then it should track changes and update the DataGridView seamlessly. It also has the advantage of not losing the users place on the grid.

    OK, here's a sample. I create a form with two buttons and one dataGridView. On button1 click, I populate the main table with some data, and bind the grid to it. Then, on second click, I create another table with the same schema. Add data to it (some that have the same primary key, and some that have new ones). Then, they merge them back to the original table. It updates the grid as expected.

        public partial class Form1 : Form
        {
            private DataTable mainTable;
            public Form1()
            {
                InitializeComponent();
                this.mainTable = this.CreateTestTable();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                for (int i = 1; i <= 10; i++)
                {
                    this.mainTable.Rows.Add(String.Format("Person{0}", i), i * i);
                }
    
                this.dataGridView1.DataSource = this.mainTable;
            }
    
            private void button2_Click(object sender, EventArgs e)
            {
                DataTable newTable = this.CreateTestTable();
                for (int i = 1; i <= 15; i++)
                {
                    newTable.Rows.Add(String.Format("Person{0}", i), i + i);
                }
                this.mainTable.Merge(newTable);
            }
    
            private DataTable CreateTestTable()
            {
                var result = new DataTable();
                result.Columns.Add("Name");
                result.Columns.Add("Age", typeof(int));
                result.PrimaryKey = new DataColumn[] { result.Columns["Name"] };
    
                return result;
    
            }
        }
    

提交回复
热议问题