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

Add control programmatically and access it via JavaScript

Hi,

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

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?

Thanks

Andre
0
andre72
Asked:
andre72
2 Solutions
 
Solar_FlareCommented:
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";
myPlaceholders.Controls.Add(tx);
AddedControls.Add(tx.ID, tx.ClientID);



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

Open in new window

0
 
aplusexpertCommented:
Hi

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

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