开发者

Why is my DataGridView not updating changes on the underlying DataTable

This is my code:

    private void button1_Click(object sender, EventArgs e)
    {
        DataTable table = new DataTable();
        using (SqlCeDataAdapter sqlCeDataAdapter = new SqlCeDataAdapter("SELECT * FROM test", sqlCeConnection))
        {
            sqlCeDataAdapter.Fill(table);
        }
        dataGridView1.DataSource = table;
    }

    private void button2_Click(object sender, EventArgs e)
    {
        MessageBox.Show(((DataTable)dataGridView1.DataSource).Rows.Count.ToString());
    }

What I'm trying to do is to update the underlying database, but acc开发者_StackOverflow社区ording to this tutorial, the underlying DataTable would need to reflect the changes made on the DataGridView whenever I edit the rows. What I'm doing is just running the app, pressing button1, then deleting some rows in the DataGridView and then pressing button2 to see how many rows I get. On this app I get the same amount of rows as before deleting rows, but if I replace dataGridView1's DataSource with a DataTable that I populate myself (By calling DataTable.NewRow() and so on), the changes are reflected on the DataTable every time I delete a row (the underlying DataTable contains less rows after I delete some of them).


Your code seems to be incomplete even if you compare it with the article that you are referring to.

In the article itself, it is the BindingSource which is used to achieve the functionality that you are trying to achieve. Refer the code below as used in that article.

//BindingSource to sync DataTable and DataGridView
BindingSource bSource = new BindingSource();

Since you seem to be learning about this, i wont give you exact code but pointers in the general direction.

See how the above object is being used in the example tutorial. That should help you simulate behaviour similar to what you are looking for.

Also, one more hint, once you make some changes after binding a grid to a data source, you do have to TELL the data source to update itself. This too is covered in the tutorial's sample code.

Hope this helps! I also suggest that you read the MSDN both related to BindingSource and DataAdapter as you need to use both in conjunction for your functionality to work as you would like it to.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜