Referencing Dynamically Drop Down Lists/Creating Non-Literal Server ID Tags

Posted on 2004-08-16
Last Modified: 2013-11-19
Ok, so I've been trying to do this seemingly simple task for several hours now, but am just missing something huge. Here's the problem:

Basically, I just want to be able to create a runtime defined number of dropdown lists and be able to reference the values, but here's the full description:

I have a dynamic number of objects, each which need a drop down list from which I can get the value. The problem comes in being able to reference the lists.

I tried to create an array of DropDownLists, and then reference them in the web form. But, I am unable to reference them on the page since I cannot figure out how to reference a control in an array. I tried modifying the id tag to do so, but entering anything other than a string gives me parsing errors.

Similarly, I tried creating the objects directly in the page and adding the elements, but again I couldn't figure out how to reference the lists since I cannot assign anything other than a literal id (if someone could tell me how to modify the server id tag dynamically that would solve this problem nicely).

So now I am envisioning a set of state variables that get modified every time the list value changes, but this seems far too complicated for such a simple task.

So, any suggestions? I would, of course, be happy to provide code or answer any question.

Thanks in advance,
Question by:ebyrne
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
LVL 17

Expert Comment

ID: 11809875
are you using find control like so?

Dim x1 As myCustomControl = DirectCast(Me.FindControl("ReportMenu1"), myCustomControl)
                myPageLabel.text = x.MyCustomControl.Label.Text

Public ReadOnly Property GetMyLabelText() As String
   If Not Label1 Is Nothing Then Return Label1.TexT
 End Get
End Property


Private _myParameter as String
Public Property myParameter() as String
    Return _myParameter
  End Get
    _myParameter = value
  End Set
End Property

Then in you aspx page:

Dim x1 As myCustomControl = DirectCast(Me.FindControl("ReportMenu1"), myCustomControl)
x1.myParameter = "XXXX"


LVL 21

Expert Comment

ID: 11809888
can you paste some code on how you are creating and displaying the controls dynamically? In General when you are adding controls dynamically to a page and wants to get their information after PostBack you need to recreate these elements after the PostBack.For e.g First create some controls like

   Dim txtName As TextBox = New TextBox
            txtName.ID = "txtName2"


After PostBack, if you want to retrieve the text entered in the textBox. If you try this:
   Dim strText as String
   strText = txtName2.Text

you'll receive an exception. Because the boxes have not been created again and the local variable txtName2 simply not exists.

So in order to retrieve you'll need to recreate the box then, you may try to get its value by using the following code:

   dim txtName2 As TextBox
   txtName2 = CType(Me.Page.FindControl("txtName2"),TextBox)
   if not txtName2 is Nothing then
   end if

You can try this technique for your drop downlists.
Hope that this helps you


Author Comment

ID: 11810013
Sorry, I think the way I phrased it led to confusion. By dynamically I meant the number of controls is specified at run time, not that I am dynamically crating the object and adding it to the page, although it might turn out that I need to do that, but it seems like it should be simpler.

Let me give an example (C#):
<% for (int i = 0; i < numOptions; i++) {%>
    <asp:DropDownList ID="XXX" Runat=server />
    [Add drop down options here, or on page load.]
<% }%>

So, for example I would have an array:
public DropDownList [] optionsLists
which I would instantiate and populate on Page_Load. I would like the tag to reference the appropriate array, optionsLists[i].

Is this possible or am I looking at this the entirely wrong way?

Do I have to use the Controls.Add method?

Also, if possible, could you use C#, but if not it's no problem.

Thanks again for your continued help.
PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now


Author Comment

ID: 11810063
Another way to explain it is that I basically want to do the same as creating a <select> object for each option with the option name in a form and posting the value. In the end, I am just hoping to have the user select values for these dropDownLists and post them to a handling page. I could just generate the form syntax, select objects, etc.., but it seems like there has to be a simple way to do this. I would hope... :)

Author Comment

ID: 11812448
Any ideas? :)
LVL 17

Expert Comment

ID: 11812518
do you mean adding list items like so:

Private Sub ddlExpDate_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlExpDate.Load
        Dim i As Integer
        Dim ExpDateItem As ListItem
        Dim InitialDate, DateToAdd As Date

        Me.ddlExpDate.Items.Clear() ' CardExpDate is a DropDownList control
        For i = 0 To 72
            If Now.AddMonths(i).Month = 1 Then
                ExpDateItem = New Web.UI.WebControls.ListItem("-----", "")
            End If
            DateToAdd = Date.Parse(Now.AddMonths(i).Month & "/" & DateToAdd.DaysInMonth(Now.AddMonths(i).Year, _
               Now.AddMonths(i).Month) & "/" & Now.AddMonths(i).Year)
            ExpDateItem = New Web.UI.WebControls.ListItem(DateToAdd.ToString("MM/yyyy"), DateToAdd.ToString("MM/dd/yyyy"))
    End Sub


Author Comment

ID: 11813226
No, adding the items is not the problem, although thanks for the suggestion anyway. I suppose the code example might be unclear. What I really need is a way to change the id tag (XXX) for each object. Thus, I could iterate through, creating a new dropDownList for each instance. Can I instantiate controls like that or do I need to use the page.add syntax?
LVL 10

Accepted Solution

jnhorst earned 500 total points
ID: 11855971
Knowing how you determine at runtime how many controls need to be created will help, but here some ideas.  It will also help to know if the options will be the same for each dropdown list, or if some will be different than others, how?

If you want these to appear in a single table cell, mark that <TD> tag as runat="server" with an id [as in <TD id="controlsHere" runat="server">.  When you build your project, Visual Studio will declare a variable named controlsHere as an HtmlTableCell.  You can then reference it in your code as follows:

for (int i=0; i < optionsNeeded; i++)
     // create the drop down list.  use the i value in the name.
     DropDownList ddl = New DropDownList();
     ddl.ID = "ddl_" + i.ToString();

     // set width and any other style issues that may apply.
     ddl.width = Unit.Pixel(300);

     // add items.
     ddl.Items.Add("text", "value");
     // ... add however many items needed, if all controls will have the same options.

     // add the control to the table cell.

Now if your formatting requires you to be a little more flexible, you can always specify a TR tag with and id and runat="server" and then dynamically create and add HttpTableCell objects to the table row, and then add the drop down list to the table cell like above.

When you go to read the value, assuming you would iterate through them like when you created them, you would do this:

for (int i=0; i < optionsNeeded; i++)
     // variable for selected data.
     string ddlSelection = "";

     // get drop down list.
     DropDownList ddl = (DropDownList)controlsHere.FindControl("ddl_" + i.ToString());
     if (ddl != null) ddlSelection = ddl.SelectedItem.Value;

     // do whatever with the value.


Author Comment

ID: 11856067
That's exactly what I was looking for. Thanks for opening my eyes. :)

Featured Post

Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Knockoutjs (Knockout) is a JavaScript framework (Model View ViewModel or MVVM framework).   The main ideology behind Knockout is to control from JavaScript how a page looks whilst creating an engaging user experience in the least …
Have you tried to learn about Unicode, UTF-8, and multibyte text encoding and all the articles are just too "academic" or too technical? This article aims to make the whole topic easy for just about anyone to understand.
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question