如何在后面的代码中将 DataGrid 绑定到 DataTable? [英] How to Bind a DataGrid to a DataTable all in code behind?

查看:24
本文介绍了如何在后面的代码中将 DataGrid 绑定到 DataTable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在后面的 C# 代码中将 DataGrid 绑定到 DataTable?(所有控件都是在运行时生成的,所以请不要使用 XAML)

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

我尝试了 Binding()、设置 DataContext、设置 ItemsSource,但都不起作用:

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;

我需要做的就是将一个DataGrid绑定到一个DataTable,这样当有新行添加到DataTable时,它会自动显示在DataGrid上.

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.

我通过 stackoverflow 和 google 搜索了所有内容,但奇怪的是我找不到解决方案.

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;

这篇关于如何在后面的代码中将 DataGrid 绑定到 DataTable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆