Michael S. Willy
Michael S. Willy

Reputation: 113

Bind DataTable to Datagridview that already have column defined

I am trying to Bind DateTable to Datagridview that already have columns designed using Designer in VS. Source for DataTable is sql database. I am trying to do this using following code which adds only blank rows in datagridview.

dataGridView1.AutoGenerateColumns = false;  // Disable autogeneration of columns

DataTable dt = new DataTable();

foreach (DataGridViewColumn col in dataGridView1.Columns)
{
    dt.Columns.Add(col.Name);
}
dt = get_data_table("select * from Mytable");
dataGridView1.DataSource = dt;

Upvotes: 3

Views: 10192

Answers (1)

gzaxx
gzaxx

Reputation: 17590

DataGridView columns have property named DataPropertyName just set them to your DataTable column names and you are set.

foreach (DataGridViewColumn col in dataGridView1.Columns)
{
    dt.Columns.Add(col.Name);
    col.DataPropertyName = col.Name;
}

this should work.

Upvotes: 3

Related Questions