【问题标题】:How to Bind a DataGrid to a DataTable all in code behind?如何在后面的代码中将 DataGrid 绑定到 DataTable?
【发布时间】:2011-08-14 11:22:59
【问题描述】:

如何在后面的 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 搜索了所有内容,但奇怪的是我找不到解决方案。

【问题讨论】:

  • 您的意思是将数据表绑定到数据网格,而不是将数据网格绑定到数据表。
  • 订阅DataTable的TableNewRow事件并赋值

标签: c# wpf datatable


【解决方案1】:

尝试绑定到数据集中的一个表:

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

【讨论】:

  • 我正要输入,我认为他将 DataGrid 绑定到 DataTable 的逻辑,所以它以错误的方式更新它。
  • @tomasmcguiness。哇 - 问题解决了。谢谢!!迫不及待地想用 5 分钟的限制来回答。顺便提一句。什么是 DefaultView?
  • DefaultView 是 DataTable 的 DataView。您可以将其用于过滤、排序。 Wpf 内部将此 DefaultView 转换为 BindingListCollectionView。因此,我始终直接绑定到 BindingListCollectionView。
【解决方案2】:

另外,为了在您的数据及其在表单上的表示之间保持良好的抽象层,我建议您将 DataGridView 的属性 AutoGenerateColumns 设置为 false 并仅添加您想要手动显示的列以及标题名称您选择的(在这种情况下,不要忘记设置列的 DataPropertyName 属性)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-12
    • 2014-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-28
    • 1970-01-01
    • 2013-03-24
    相关资源
    最近更新 更多