• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 513
  • Last Modified:

Add control programmatically and access it via JavaScript


I like to add a control programmatically to a placeholder like:
TextBox tx = new TextBox();
tx.ID = "myControl";

Works fine and is not the problem.

But when I place a control fix at my page I can access it from JavaScript like $find(<%= myControl.ClientID %>);
This works no more with the programmatically way.
How can I access it in this way?


2 Solutions
Yes, the server side script block <%= myControl.ClientID %> will not work as the control is not a property of the page class in the same way that your design-time controls are.

I think your best bet will be to store the ClientIDs of the newly added controls as you create them, perhaps something like this:
(I havent tested it, but it shows what you need to do - store the ClientID as you go and then be able to access that clientid from code blocks in the .aspx page)

add public property to your page class

public class MyPage : System.Web.UI.Page
   public Dictionary<string, string> AddedControls = new Dictionary<string, string>();

   ...all the rest of your code


then when creating controls
TextBox tx = new TextBox();
tx.ID = "myControl";
AddedControls.Add(tx.ID, tx.ClientID);

//then in the page
<%= AddedControls["myControl"] %>

Open in new window


Please use the document.getElementbyID method to get the control in place of $find.
andre72Author Commented:
Thanks for your support

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now