设置用户控件的属性值 - C#
我创建了 4 个用户控件,它们或多或少具有相同的属性。以下是用户控件源的示例:
<div>
<asp:Label runat="server" ID="LabelPrompt"></asp:Label>
<telerik:RadComboBox runat="server" ID="ComboBoxInput"></telerik:RadComboBox>
</div>
当页面加载时,我需要更改 LabelPrompt 的值。这就是我正在做的事情:
Control p = LoadControl("~/Parameters/TextBoxParameterUserControl.ascx");
p.GetType().GetProperty("LabelPrompt").SetValue(p, "AAAA", null);
PanelParametersList.Controls.Add(p);
以前我尝试使用下面的代码来添加用户控件,但它不起作用。另一个线程建议我使用上面的代码,它有效(就将控件添加到视图而言)。
PanelParametersList.Controls.Add(new TextBoxParameterUserControl());
不管怎样,编译器在下面一行抱怨:
p.GetType().GetProperty("LabelPrompt").SetValue(p, "AAAA", null);
但这不起作用,它说“对象未设置为引用”......我做错了什么?
ps 我知道超级/子分类是可能的,但这不是我想要的!
I have created 4 user controls that more or less have the same properties. Here is an example of the source for the user control:
<div>
<asp:Label runat="server" ID="LabelPrompt"></asp:Label>
<telerik:RadComboBox runat="server" ID="ComboBoxInput"></telerik:RadComboBox>
</div>
When the page loads I need to change the value of LabelPrompt. Here is what I am doing:
Control p = LoadControl("~/Parameters/TextBoxParameterUserControl.ascx");
p.GetType().GetProperty("LabelPrompt").SetValue(p, "AAAA", null);
PanelParametersList.Controls.Add(p);
Previously I tried to use the code below to add a user control but it didn't work. Another thread suggested I used the above code, which works (in terms of adding the control to the view).
PanelParametersList.Controls.Add(new TextBoxParameterUserControl());
Anyway, the compiler complains at the following line:
p.GetType().GetProperty("LabelPrompt").SetValue(p, "AAAA", null);
But this doesn;t work, it says 'Object not set to a reference'.....What am I doing wrong?
p.s. I am aware that super/sub classing is possible, but this is not what I am after!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是否尝试过类似的操作(我希望您在运行时有意加载这些控件?):
当然,
LabelPrompt
属性必须是public
。Have you tries something like this (and I hope you are intentionally loading these controls at runtime?):
Of course the
LabelPrompt
property must bepublic
.