Solved

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

Posted on 2004-08-16
9
276 Views
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,
Gene
0
Comment
Question by:ebyrne
9 Comments
 
LVL 17

Expert Comment

by:AerosSaga
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
 Get
   If Not Label1 Is Nothing Then Return Label1.TexT
 End Get
End Property


OR

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

Then in you aspx page:

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

Regards,

Aeros
0
 
LVL 21

Expert Comment

by:tovvenki
ID: 11809888
Hi,
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"

            tc1.Controls.Add(txtName)
            tr.Cells.Add(tc1)


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
      Response.Write(txtName2.Text)
   end if

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

regards,
venki
0
 
LVL 2

Author Comment

by:ebyrne
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++) {%>
<tr>
  <td>Option:</td>
  <td>
    <asp:DropDownList ID="XXX" Runat=server />
    [Add drop down options here, or on page load.]
  </td>
</tr>      
<% }%>

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.
0
 
LVL 2

Author Comment

by:ebyrne
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... :)
0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 2

Author Comment

by:ebyrne
ID: 11812448
Any ideas? :)
0
 
LVL 17

Expert Comment

by:AerosSaga
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("-----", "")
                Me.ddlExpDate.Items.Add(ExpDateItem)
            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"))
            Me.ddlExpDate.Items.Add(ExpDateItem)
        Next
    End Sub

0
 
LVL 2

Author Comment

by:ebyrne
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?
0
 
LVL 10

Accepted Solution

by:
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.
     controlsHere.Controls.Add(ddl);
}

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.
     ...
}

John
0
 
LVL 2

Author Comment

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

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Shoutout to Emily Plummer (http://www.experts-exchange.com/members/eplummer26.html) for giving me this article! She did most of it, I just finished it up and posted it for her :)    Introduction In a previous article (http://www.experts-exchang…
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 …
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:
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

708 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now