Go Premium for a chance to win a PS4. Enter to Win


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

Posted on 2004-08-16
Medium Priority
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
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.
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.


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 2000 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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

Introduction Since I wrote the original article about Handling Date and Time in PHP and MySQL several years ago, it seemed like now was a good time to update it for object-oriented PHP.  This article does that, replacing as much as possible the pr…
Without even knowing it, most of us are using web applications on a daily basis.  In fact, Gmail and Yahoo email, Twitter, Facebook, and eBay are used by most of us daily—and they are web applications. We generally confuse these web applications to…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Suggested Courses

916 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