数据绑定到programmaticly创建数据表
假设我有这样一个数据表:
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
任何想法,为什么这个工程上的数据表通过一个DataAdapter创建的,而不是在一个programmaticly创建了一个?
Any idea why this works on a datatable created by a dataAdapter, but not on a programmaticly created one?
OK,你的code搞乱了一段时间后,我一直得到难倒。后来我终于意识到这个问题。我假设_dtRow是一个DataRow。您需要引用实际的数据表(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");
编辑:看到关于伊戈尔的后您的评论之后。如果您绑定到dt的,然后说,例如,如果你有一个DataGridView绑定到该数据表中,您可以选择不同的行每一次,文本框会改变。
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.
这里的code,它为我的作品:
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");
更改在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.