DataGridView Doesn't Reflect Changes Made on DataTable

45 Views Asked by At

I'm struggling with getting my DataGridView to bind to my DataTable, so I decided to try a super simple example.

        DataTable dataTable = new DataTable();

        dataTable.Columns.Add("ID", typeof(int));
        dataTable.Columns.Add("Name", typeof(string));
        dataTable.Columns.Add("Age", typeof(int));

        dataTable.Rows.Add(1, "John", 25);
        dataTable.Rows.Add(2, "Jane", 30);
        dataTable.Rows.Add(3, "Bob", 40);

        DataGridView dataGridView = new DataGridView();
        dataGridView.DataSource = dataTable;

However, even after this code gets executed, dataGridView.Rows.Count is still 0, and I'm struggling to understand why. I've tried multiple other things as well (used BindingSource with RefreshBindings, tried turning off AutoGenerateColumns, etc).

How can I populate my DataGridView using the DataTable? Am I missing somthing obvious?

1

There are 1 best solutions below

1
RomeoWithAllTheToxins On

dataTable.Columns.Add("ID", typeof(int));
dataTable.Columns.Add("Name", typeof(string));
dataTable.Columns.Add("Age", typeof(int));

dataTable.Rows.Add(1, "John", 25);
dataTable.Rows.Add(2, "Jane", 30);
dataTable.Rows.Add(3, "Bob", 40);
dataTable.SaveChanges();

// Make sure to create the DataGridView after the DataTable is populated
DataGridView dataGridView = new DataGridView();
dataGridView.AutoGenerateColumns = true; // Enable AutoGenerateColumns to create columns automatically
dataGridView.DataSource = dataTable;

this.Controls.Add(dataGridView);