开发者

How to access UserConrtorl's controls in this situation

  1. I have an UpdatePanel.
  2. and I have a PlaceHolder inside this UpdatePanel.
  3. There is a number of UserControls. One of them will be loaded dynamically, according to some selections.

    Co开发者_开发技巧ntrol mycontrol = this.Page.LoadControl("myusercontrol.ascx");
    myplaceholder.Controls.Add(mycontrol);
    
  4. after loading a specific UserControl, I wanted to get the text written in a TextBox that is in the loaded UserControl from the Parent page.

    TextBox mytextbox = (TextBox) Page.FindControl("myusercontrol")
        .FindControl("mytextbox");
    

The problem was the text is always empty !

What am I missing ? I appreciate your help.


You should load your UserControl overriding OnInit as mentioned before. And why were you looking entire page to find the UserControl? You can use PlaceHolder.Controls...

This how I got it work

protected override void OnInit(EventArgs e)
{
    Control userControl = this.Page.LoadControl("WebUserControl.ascx");
    testPlaceHolder.Controls.Add(userControl);
    userControl.ID="id"; 
    base.OnInit(e);
}
protected void testButton_Click(object sender, EventArgs e)
{
    Control testUserControl = (Control)testPlaceHolder.Controls[0];
  //Control testUserControl=(Control)testPlaceHolder.FindControl("id");
    TextBox mytextbox = (TextBox)testUserControl.FindControl("testTextBox");
    testButton.Text = mytextbox.Text;
}


When you say that the text is always empty, do mean the TextBox object is null or literally the .Text of the textbox is empty?

Remember that in web applications you have to post back to the server to refresh results and update controls among other things.

Try posting back to the server and seeing if that helps.


Have you considered adding a property to your user control to return the text?

eg:

public class YourControl : UserControl
{

  public string Text
  {
    get
    {
      return this.TextBox1.Text;
    }
  }
}


Usually, User Controls are used for encapsulation - you wrap up all the details of controls, behaviour etc in a UC so other code doesn't have to deal with it.

By referring to controls within the UC directly - by name or ID - you're breaking the model. Can I suggest you don't do this, instead if you need to get information from the UC you add a property, event or method to it that the container can call.

That way if you need to change the UC - control names, types, styles, or additional logic is used later - you only need to change that property/event/method in the UC, not in the (for example) 100 places it might be used in the code.

If you could let us know why you need this information or more specific details about the example, perhaps we can suggest some code to implement this.


So, what should I do ?

Just get the posted values manually.

Request.Form[yourcondeol.UniqueID]

by debugging this you can see all the posted data.

Request.Form
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜