Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Use same code for multiple drop dpwn lists

Status
Not open for further replies.

beaniebear

Programmer
Sep 14, 2001
93
GB
I'm sorry this is probably a very simple question. I haev four drop dpwn lists called ddl1, ddl2, ddl3 and ddl4.

On page submit I want to run the same code on each ddl and wanted to do a for loop and dynamically put in the name of the ddl I want to reference.

Any help much appreciated, thanks.
 
Do you really need to pass the name, or can you just pass the control e.g.
Code:
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        DoSomething(DropDownList1)
        DoSomething(DropDownList2)
    End Sub

    Private Sub DoSomething(ByRef DDL As DropDownList)
        Response.Write(DDL.SelectedItem.Value)
    End Sub

Mark,

Darlington Web Design[tab]|[tab]Experts, Information, Ideas & Knowledge[tab]|[tab]ASP.NET Tips & Tricks
 
Thanks.

I was kind of hoping I could just call one sub that would loop through and perform a task on each ddl.

I think I need to use Me.Controls.Item("ddl" & x) using a for loop from x=1 to 4

But I'm getting the error "Conversion from string "ddl1" to type 'Integer' is not valid"

???
 
bean,

that is because you are putting a string and an int together.. try Me.Controls.Item("ddl" & x.ToString())

Running in circles is what I do best!
 
bean,

that is because you are putting a string and an int together.. try Me.Controls.Item("ddl" & x.ToString())
That won't work either as the Item method takes an Integer value. Also, you don't know where abouts in the controls collection the DropDownList will be.

If you really wan't to do it in a loop, you can either:

1. Add each control to a collection and call the function for each item in the collection
2. Use a recursive loop to loop through every control and check for its type
3. Use a loop like in your example but use the FindControl method to get a reference to each DropDownList control (note you will have to use this method on the correct parent so make sure you look at the controls hierarchy first).

Mark,

Darlington Web Design[tab]|[tab]Experts, Information, Ideas & Knowledge[tab]|[tab]ASP.NET Tips & Tricks
 
Seems awfully complicated to do something quite simple.

Thanks for your help guys.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top