Search code examples
c#asp.netuser-controls

Access Textbox on Page from User Control in ASP.net


I have a some pages that are slightly different, but all have the same "action buttons" that do the same tasks for each page. Instead of duplicating the code, I made a user control that includes buttons that perform actions - but there's one action I can't seem to do.

Each page has a textbox (that's not inside the user control, as it's in a different location of the page). When I click the "Save comment" button (that is within the User Control), I can't seem to access the text in the Textbox.

I have tried using something like this:

TextBox txtComments = (TextBox)this.Parent.FindControl("txtComments");
SaveChanges(txtComments.Text);

...but txtComments comes back as null.

So, I'm wondering if this is possible, or perhaps if there's a better way to do what I'm trying to do?

Edit: The Textbox is in a Placeholder on the original page...

Edit 2: Posting minified solution - still can't figure this one out.

Edit 3: Removed solution to conserve space - resolved the issue.


Solution

  • My solution ended up being surprisingly simple....

    TextBox txt = this.Parent.Parent.FindControl("ContentPlaceHolder2").FindControl("TextBox1") as TextBox;
    if (txt != null) Label1.Text = txt.Text;
    

    Where I was going wrong before was that I was using the wrong ContentPlaceHolder ID. I was using the ID of the placeholder in the page, rather than the ID from the Master Page.