Question

I am trying to bind DataTable to DataGridView as below;

DataTable table = new DataTable();
foreach (ConsumerProduct c in ctx.ConsumerProducts)
{
    DataRow row = table.NewRow();
    row["Id"] = c.ID;
    row["Model"] = c.Model;
    row["Status"] = "Offline";

    table.Rows.Add(row);
}
dataGridView1.DataSource = table;

I get exception at the first line itself row["Id"]

Column 'Id' does not belong to table .

P.S. I have already added these columns in the designer view of dataGridView.

Was it helpful?

Solution

You just created a blank DataTable and then you are trying to add data to particular columns like Id, Model and Status.

You have to add those columns as well.

DataTable table = new DataTable();
table.Columns.Add("Id");
table.Columns.Add("Model");
table.Columns.Add("Status", typeof(string)); //with type

There is no issue in biding.

Also you can project your required column to an Anonymous type and then bind that to your data grid like:

var result = ctx.ConsumerProducts
                .Select(r=> new 
                {
                    Id = r.ID, 
                    Model = r.Model,
                    Status = "Offline"
                }).ToList();
dataGridView1.DataSource = result;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top