如何将 DataGrid 绑定到 DataTable 全部在代码隐藏中?
如何在 C# 代码后面将 DataGrid 绑定到 DataTable? (所有控件都是在运行时生成的,因此请不要使用 XAML)
我尝试了 Binding()、设置 DataContext、设置 ItemsSource,但都不起作用:
/* 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;
我需要做的就是将 DataGrid 绑定到 DataTable,因此,当有新行添加到 DataTable 时,它将自动显示在 DataGrid 上。
我通过 stackoverflow 和 google 进行了搜索,但奇怪的是我找不到解决方案。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试绑定到数据集中的表之一:
Try binding to one of the Tables in your dataset:
另外,为了在数据及其在表单上的表示之间保持良好的抽象层,我建议您将 DataGridView 的属性 AutoGenerateColumns 设置为 false 并仅添加您想要手动显示的列,并使用您选择的标题名称(在这种情况下,不要忘记设置列的 DataPropertyName 属性)。
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).