开发者

Setting a textbox text in usercontrol from page

开发者 https://www.devze.com 2023-02-06 07:44 出处:网络
I have a usercontrol which contains a textbox. I now want to add variable to that user control, lets call it Text, which will populate the textbox with the value passed in. I thought this could be don

I have a usercontrol which contains a textbox. I now want to add variable to that user control, lets call it Text, which will populate the textbox with the value passed in. I thought this could be done in the "set" of the variable in the code behind of the user control.

public string Text
{
    get {}
    set
    {
        txtBox.Text = value;
    }
}

txtBox is the ID of the textbox within the usercontrol. Does anyone know how this can be done?

Thanks

Edit The problem I 开发者_运维技巧suspect is that I am setting the text value in the Page_Load of the page hosting the user control. Where should I be setting this value?


If your problem is that txtBox is null then I can suggest you the following:

If you're creating a user control dynamically then don't forget to add it to the page's control tree BEFORE (implicitly or explicitly) accessing its child controls. Otherwise all these child controls will remain uninitialized:

MyUserControl ctrl = (MyUserControl )Page.LoadControl("~/MyUserControl.ascx");
base.Controls.Add(ctrl);

ctrl.Text = "some value";

If your user control is declared in the page's markup then don't forget to register using the Register directive with the "Src" property set to location of your user control:

<%@ Register TagPrefix="controls" TagName="MyUserControl" 
    Src="~/MyUserControl.ascx" %>

<controls:MyUserControl id="ctrl1" Text="some value" runat="server" />

Registering the user control using the following technique WILL NOT work (not the case if all child controls are created dynamically. But then you don't need a user control - you just need a class derived from the Control class):

<%-- Will not work for user controls --%>
<%@ Register Assembly="MyControlsAssembly.Shell" Namespace="MyControls" 
    TagPrefix="controls" %>

Hope this will help you.

0

精彩评论

暂无评论...
验证码 换一张
取 消