数据绑定到以编程方式创建的 DataTable [英] Databinding to a programmatically created DataTable

查看:47
本文介绍了数据绑定到以编程方式创建的 DataTable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个这样的数据表:

Suppose I have a datatable like this:

        DataTable dt = new DataTable("Woot");

        dt.Columns.AddRange(new DataColumn[]{
            new DataColumn("ID",typeof(System.Guid)),
            new DataColumn("Name",typeof(String))
            });

当我尝试将控件绑定到它时:

When I try to bind a control to it:

        this.txtName.DataBindings.Add("Text", _dtRow, "Name");

我得到了这个例外:

无法绑定到属性或列数据源上的名称.范围名称:数据成员

Cannot bind to the property or column Name on the DataSource. Parameter name: dataMember

知道为什么这适用于由 dataAdapter 创建的数据表,但不适用于以编程方式创建的数据表吗?

Any idea why this works on a datatable created by a dataAdapter, but not on a programmaticly created one?

推荐答案

好吧,在把你的代码弄乱了一段时间之后,我一直很困惑.然后我终于意识到了这个问题.我假设_dtRow 是一个DataRow.您需要参考实际的 DataTable (dt).

OK, after messing with your code for a while, I kept getting stumped. Then I finally realized the issue. I'm assuming _dtRow is a DataRow. You need to reference the actual DataTable (dt).

this.textBox1.DataBindings.Add("Text", dt, "Name");

在看到您对 Igor 帖子的评论后.如果你绑定到 dt,然后比如说如果你有一个 datagridview 绑定到这个 DataTable,每次你选择不同的行时,文本框都会改变.

After seeing your comment on Igor's post. If you bind to dt, then say for example if you have a datagridview bound to this DataTable, every time you select a different row, the textbox will change.

这是适合我的代码:

            DataTable dt = new DataTable("Woot");

            dt.Columns.AddRange(new DataColumn[]{
            new DataColumn("ID",typeof(System.Guid)),
            new DataColumn("Name",typeof(String))
            });


            dt.Rows.Add(Guid.NewGuid(), "John");
            dt.Rows.Add(Guid.NewGuid(), "Jack");

            this.dataGridView1.DataSource = dt;

            this.textBox1.DataBindings.Add("Text", dt, "Name");

更改 DGV 中的行,您将看到文本框更改文本.

Change rows in the DGV and you'll see the textbox change text.

EIDT AGAIN 好的,是时候破解它了.这就是我让它工作的方式:

EIDT AGAIN OK, time to hack it. This is how I got it to work:

this.textBox1.DataBindings.Add("Text",_dtRow.ItemArray[1], ""); 

我使用了索引 1,但您可以使用数组中所需的任何索引.

I used index 1, but you can use whatever index you need in the array.

这篇关于数据绑定到以编程方式创建的 DataTable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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