views:

668

answers:

2

Say a DataGridView has its DataSource property set to a DataView instance.

DataGridView dgv;
DataTable dt;

// ... dt gets populated.

DataView dv = dt.DefaultView;

dgv.DataSource = dv;

// ... dt gets modified

// The DataGridView needs to update to show these changes visually
// What goes here?

I know you could set dgv.DataSource to null, then back to dv. But that seems pretty weird. I'm sure there are a couple of other ways, too. But what's the correct, official way to do this?

+2  A: 

The correct way is for the data-source to implement IBindingList, return true for SupportsChangeNotification, and issue ListChanged events. However, AFAIK, a DataView does this...

Marc Gravell
+1  A: 

I'm pretty sure that if you're DataGridView is bound to the DefaultView of a DataTable, and the Table changes, the changes are automatically reflected in the DataGridView. Have you tried this and are having problems? Post the code you have that updates the DataTable, maybe something else is wrong. In fact, here's a small sample app I just wrote:

public partial class Form1 : Form
    {
        private DataTable table;

        public Form1()
        {
            InitializeComponent();
            table = new DataTable();
            this.LoadUpDGV();
        }

        private void LoadUpDGV()
        {
            table.Columns.Add("Name");
            table.Columns.Add("Age", typeof(int));

            table.Rows.Add("Alex", 27);
            table.Rows.Add("Jack", 65);
            table.Rows.Add("Bill", 22);
            table.Rows.Add("Mike", 36);
            table.Rows.Add("Joe", 12);
            table.Rows.Add("Michelle", 43);
            table.Rows.Add("Dianne", 67);

            this.dataGridView1.DataSource = table.DefaultView;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            table.Rows.Add("Jake", 95);
        }
    }

Basically, when the form loads up, it just populates the table with names and ages. Then it binds that to the DGV. On button click, it adds another row to the DataTable itself. I tested it, and sure enough it showed up in the grid without any issues.

BFree