Creating the Form

To demonstrate how to locate controls dynamically, we will need to create a simple web site with some controls on it. Then, we will access these controls dynamically through event arguments. To begin, create a new ASP.NET Empty Web Site and:

  1. Right click the project in your solution explorer.
  2. Select add new item…
  3. Select a web form.
  4. Name it ‘Default.aspx’.
  5. Click add.
  6. Open Default.aspx up to source mode.
  7. Drag and drop a label onto the web form.
  8. Add a break line.
  9. Drag and drop a label onto the web form.
  10. Change the ID property to ‘ResultsLabel’.
  11. Add a break line.
  12. Drag and drop a textbox onto the web form.
  13. Set the Text property to ‘test1′.
  14. Drag and drop a textbox onto the web form.
  15. Set the Text property to ‘test2′.
  16. Drag and drop a textbox onto the web form.
  17. Set the Text property to ‘test3′.
  18. Add a break line.
  19. Drag and drop a repeater onto the web form.
  20. Changed the ID property to ‘MyDataList’.
  21. Add an itemtemplate to the repeater.
  22. Drag and drop a label into the itemtemplate.
  23. Change the ID property to ‘MyLabel’.
  24. Change the Text property to ‘<%# Container.DataItem.ToString() %>’.
  25. Add a break line.
  26. Drag and drop a button onto the web form.
  27. Drag and drop a button onto the web form.

This has setup a form with some labels, textboxes, buttons, and a repeater. We will use the two buttons to display some data from our controls dynamically. To begin, open Default.aspx up to design mode and double click Button1. Then, add the following code to that event method:

This will loop through every control on the page, check to see if it is a text box, and then display the value of every text box on the page in our first label. Next, open Default.aspx up to design mode and double click Button2. Then, add the following code to that event method:

This code will give our repeater some temp data and loop through the controls in the repeater. Then, it will display the container type and type of each control.

Testing

To test this out load up the web site. Click the first button and ensure that our first label displays the text from our text boxes. Click the second button and ensure that the second label displays the container and control types of each of the three items in our repeater. This demonstrates how you can access the controls on your page dynamically without knowing their individual ID’s.

Download Source Files