user1672097
user1672097

Reputation: 351

Dynamically bind DataGridView in the Windows Form

I want to bind a DataTable in a Windows form in runtime. I have created the form in runtime and tring to bind the Data table into the gridview of the form. But it's not showing data in the form. I had used following code:

frmSearch frm = new frmSearch();
for (int i = 0; i < erpData.ERPDataTable.Columns.Count; i++)
{
    frm.Controls["grdSearch"].DataBindings
        .Add("DataSource", erpData.ERPDataTable,
                         erpData.ERPDataTable.Columns[i].ToString());
}

frm.Show();

What could be the problem? Can anyone provide an alternative solutions?

Upvotes: 1

Views: 1619

Answers (1)

itsmatt
itsmatt

Reputation: 31406

You can bind a DataGridView to some datasource in three steps:

// Create a binding source
var bs = new BindingSource();

// set the bindingsource's datasource, in this case your table
bs.DataSource = erpData.ERPDataTable;

// set the datagridview's datasource, DataSource isn't a property on Control,
// so cast the one you get from your form's Controls collection as a DataGridView
var dgv = (DataGridView)frm.Controls["grdSearch"];
dgv.DataSource = bs;

MSDN reference on binding DataGridView

Upvotes: 3

Related Questions