简体   繁体   English

如何对动态创建的控件进行数据绑定?

[英]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作为objectControl ,并且需要将其TextBoxTextBox ,则需要第二组括号

((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.

相关问题 如何将AutoCompleteExtender绑定到动态创建的控件? - How can I bind AutoCompleteExtender to dynamically created control? 如何向动态创建的(C#)元素添加“必需”属性? - How can I add a “Required” attribute to a dynamically-created (C#) element? 如何在两个动态加载的用户控件之间进行数据绑定? - How do I data-bind between two dynamically loaded user controls? 尝试在动态创建的程序集上绑定动态方法会导致RuntimeBinderException - Attempting to bind a dynamic method on a dynamically-created assembly causes a RuntimeBinderException 如何对标签进行数据绑定 - How to data-bind a label 如何在运行时将方法附加到动态创建的C#类型? - How do I attach a method to a dynamically-created C# type at runtime? 如何缩进(添加填充)到GridView中动态创建的列? - How to indent (add padding) to a dynamically-created column in a GridView? 如何将dataGridView对象与动态创建的类列表绑定 - How can I bind a dataGridView object with dynamically created class list 如何在Linq中将动态创建的字符串用作WHERE条件 - How to use a dynamically-created string as a WHERE condition in Linq 如何在动态创建的RadGrid中从动态创建的控件中检索和保存数据 - How do I retrieve and save the data out of a dynamically created control in a dynamically created RadGrid
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM