简体   繁体   中英

How to Bind a DataGrid to a DataTable all in code behind?

How to bind a DataGrid to a DataTable in C# code behind? (All controls are generated in run-time, so no XAML please)

I tried Binding(), set the DataContext, set the ItemsSource, but all doesn't work:

/* Binding() fails */
Binding bind = new Binding();
bind.Source = dataset;
bind.Path = new PropertyPath("dataset.Tables");
datagrid.SetBinding(DataSet, bind);

/* DataContext fails */
datagrid.DataContext = dataset.Tables;

/* ItemsSource fails */
datagrid.ItemsSource = dataset.Tables;

All I need to do is to Bind a DataGrid to a DataTable, so when there is new rows added to the DataTable, it will show automatically on the DataGrid.

I search all through stackoverflow and google but strangely I cannot find a solution.

Try binding to one of the Tables in your dataset:

datagrid.ItemsSource = dataset.Tables[0].DefaultView;

Also, to keep a good abstraction layer between your data and its representation on your forms, I would suggest you to set the property AutoGenerateColumns of your DataGridView to false and add just the columns you want displayed by hand, with the header name of your choice (in this case, do not forget to set the columns' DataPropertyName property).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM