[英]How can I data-bind a dynamically-created control?
In the past, I've created data bindings like so: 在过去,我创建了数据绑定,如下所示:
textBoxPlatypusName.DataBindings.Add(new Binding("Text", PlatypusInfo, "PlatypusName"));
...but with dynamically-created controls, this is not possible (the compiler wouldn't be able to recognize "textBoxPlatypusName" at compile-time). ...但是使用动态创建的控件,这是不可能的(编译器在编译时无法识别“textBoxPlatypusName”)。
Trying this: 试试这个:
TextBox tb = (TextBox)this.Controls.Find("textBoxPlatypusName", true).First();
(TextBox)tb.DataBindings.Add(new Binding("Text", PlatypusInfo, "PlatypusName"));
...gives me, " Cannot convert type 'void' to 'System.Windows.Forms.TextBox' " and " Only assignment, call, increment, decrement, and new object expressions can be used as a statement " ...给我,“ 无法将类型'void'转换为'System.Windows.Forms.TextBox' ”和“ 只有赋值,调用,递增,递减和新对象表达式才能用作语句 ”
Is there a way to accomplish this? 有没有办法实现这个目标?
Remove the type casting. 删除类型铸件。 It is not required, since tb
is already strongly typed as TextBox
. 这不是必需的,因为tb
已经强类型为TextBox
。 The casting is wrong here anyway. 无论如何,这里的铸造是错误的。
TextBox tb = (TextBox)this.Controls.Find("textBoxPlatypusName", true).First();
tb.DataBindings.Add(new Binding("Text", PlatypusInfo, "PlatypusName"));
If tb
was typed as object
or Control
, for instance, and you needed to cast it to TextBox
, you would need a second set of parentheses 例如,如果输入tb
作为object
或Control
,并且需要将其TextBox
为TextBox
,则需要第二组括号
((TextBox)control).SomePropertyOfTextBox = x;
Otherwise the casting is applied to the entire expression. 否则,强制转换将应用于整个表达式。 In your case, C# wants to apply the casting to the result of the Add
method, which is void
and cannot be casted. 在您的情况下,C#想要将转换应用于Add
方法的结果,该方法是void
,无法转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.