且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

数据绑定到一个编程创建的DataTable

更新时间:2023-10-07 11:27:22

好的,在搞砸你的代码一段时间后,我一直在被困扰。然后我终于意识到了这个问题。我假设_dtRow是一个DataRow。您需要参考实际的DataTable(dt)。

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

编辑:看到您对Igor发表的评论后。如果绑定到dt,那么说如果你有一个datagridview绑定到这个DataTable,每次你选择一个不同的行,文本框会改变。



这是代码适用于我:

  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中的行,您将看到文本框更改文本。



EIDT AGAIN 确定,时间到了。这是我如何工作:

  this.textBox1.DataBindings.Add(Text,_ dtRow.ItemArray [1 ],); 

我使用索引1,但可以使用数组中需要的任何索引。


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");

I get this exception:

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

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

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");

EDIT: 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.

Here's the code that works for me:

            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");

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

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

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

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