pavan
pavan

Reputation: 7

Accessing aspx value from an user control

H,

My aspx page has a usercontrol where the usercontrol contains a button. Onclick of button in usercontrol i am trying to fire javascript method. So when I click on button on to execute the javascript somehow i want to access the textbox value from the aspx page.

something like

this.getElementbyID[txtbox].value.

Is it possible? or is there any other way to access control of aspx page from usercontrol.

Thanks in advance, Pavan

Upvotes: 1

Views: 2040

Answers (3)

KV Prajapati
KV Prajapati

Reputation: 94625

Use FindControl method in code-behind of user control. Suppose .aspx page has TextBox1 control and that .aspx page is a parent of "said" user control then you may add following line into click handler of button in user control.

TextBox tx = (TextBox)Parent.FindControl("TextBox1");

Upvotes: 1

Brian Mains
Brian Mains

Reputation: 50728

Yes there are several ways to do it. A user control renders directly to the browser, so you can access an element by an ID from anywhere. I would do it this way personally; you can add a property to the user control code behind:

public string TextBoxID
{
   get { return this.TextBox1.ClientID; }
}

Then in the page, you can access the ID in client-side javascript using:

document.getElementById('<%= ucUserControlID.TextBoxID %>').value

The problem you are going to have is that if the textbox in the user control is in a page with a master page, the ID will be ct100_contentplaceholder_somecontainer_usercontrolcontainer_textboxID (something like that). The trick to circumvent this is to use an approach like document.getElementById("<%= TextBox1.ClientID %>") but that only works if the control is in the same container where this statement is. Since the control is in the user control, and the JS in the page, a property to return the client ID works well.

Upvotes: 0

Pankaj Kumar
Pankaj Kumar

Reputation: 1768

Yes its possible since after rendering the entire page(aspx page + user controls) are treated as one page.

so you can use any valid javascript to access the element as long as you know the Client Id of the control that you are seaching.

i would put this code in the user control

 <script type="text/javascript">
        $(document).ready(function () {
            $('#yourButtonID').click(function () {
                //search for your element
               alert( $('input[id$="TextBox1"]').val());
            });
        });
    </script>

hope this helps!

Upvotes: 3

Related Questions