开发者

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);
开发者_Go百科
/* 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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜