[英]Setting the value of a property for a user control - C#
I have created 4 user controls that more or less have the same properties. 我创建了4个或多或少具有相同属性的用户控件。 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. 页面加载时,我需要更改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? 但这是行不通的,它说“对象未设置为引用” .....我在做什么错?
ps I am aware that super/sub classing is possible, but this is not what I am after! ps我知道可以进行超级/子分类,但这不是我所追求的!
Have you tries something like this (and I hope you are intentionally loading these controls at runtime?): 您是否尝试过类似的方法(并且希望您在运行时有意加载这些控件?):
TextBoxParameterUserControlic control = LoadControl("~/Parameters/TextBoxParameterUserControl.ascx") as TextBoxParameterUserControl;
if(control != null)
{
control.LabelPrompt = "AAAA";
PanelParametersList.Controls.Add(p);
}
Of course the LabelPrompt
property must be public
. 当然, LabelPrompt
属性必须是public
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.