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

Method to utilize controls dynamically based on param passed in.....(this is possible, no?)

Hi everyone,

I am just curious- is it possible to have a method that takes an string as a parameter which passes in a number (1,2,3,4,etc) that is appended to the control values in order to have the same method work for a number of different controls (which are separated by panels, etc.)?

For instance (I know this won't work- but to get an idea of what I want to know):

((I would have several groups of ASP.NET controls with the same properties, but with names being differentiated by an appended number---->> ie. ddlDrop1, ddlDrop2, ddlDrop3, ddlDrop4......txtNew1, txtNew2, txtNew3, txtNew4, etc.))

   protected void DynamicControlMethod(string inputNum)

            ddlDrop + inputNum + .SelectedIndex = 0;

            txtNew + inputNum + .Text = "something";



NOTE: I am not actually trying to do anything in the above- I just want to know how I can dynamically use the controls based on the 'inputNum' param. This must somehow be possible in C#, right?

Thanks a bunch in advance to all!!

  • 2
1 Solution
Bob LearnedCommented:
You need to use FindControl to get a reference to a control dynamically.  FindControl without UniqueID, needs to have a reference to the parent control, such as a Panel:

   Get a reference to a TextBox on the main page:
      TextBox txt = this.FindControl("TextBox1");

   Get a reference to a Label on a panel:
     Label lbl = this.panel1.FindControl("Label1");

   Get a reference to a Button, using an expression:
      int index = 5;
     Button btn = this.FindControl("Button" + index);

Try to use FindControl method of the controls' container.
Oops, one minute difference :-)
EllsworthAdhesivesAuthor Commented:
Thank you TheLearnedOne- that's exactly what I was looking for.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

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.

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