简体   繁体   中英

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

ps I am aware that super/sub classing is possible, but this is not what I am after!

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM