Search code examples
asp.netvb.netoopdrop-down-menufindcontrol

How to find the value of a dropdownlist using FindControl?


I am working on a website with VB.NET and ASP.NET. I currently have recurring DropDownLists for the user to provide input.

The design is recurring. These DropDownLists get their values from a database table, Everything with the Web interface is working except for writing these recurring values to the database - that is just to give you some background.

I have set the ID's of each DropDownList like so:

FrequencyList.ID = String.Concat("FreqList", DBReader(0))

That is in a loop while reading the DatabaseReader.

This is what I'm having issues with (please note I simplified the code down to make it easier to read:

    Dim i As Integer
    DBCommand = New SqlCommand()

    DBCommand.Connection = DBConnection
    DBCommand.CommandType = Data.CommandType.StoredProcedure
    DBCommand.CommandText = "StoredProcedureName"
    DBConnection.Open()
    For i = 1 To AspectTableLength


        Dim ParamFrequencyID As SqlParameter = DBCommand.Parameters.Add("@nFrequencyID", SqlDbType.Int)
        ParamFrequencyID.Value = FindControl("FreqList" & Convert.ToString(i))
        ParamFrequencyID.Direction = ParameterDirection.Input
    Next

The FindControl("FreqList" & Convert.ToString(i)) variable is incorrect because it does not access the value - and adding .SelectedItem.Value does not work.


Solution

  • I got help from a developer.

    Dim MyControls As ControlCollection = Panel.Controls
            Dim Number As Integer 'this is the same as "DBReader(0)"
    
            For Each MyControl As Control In MyControls
                If MyControl.ID Is Nothing Then
                Else
                    If MyControl.ID.StartsWith("Span") Then
                        Number = Replace(MyControl.ID, "Span", "")
                        Dim Freq As DropDownList = PanelMain.FindControl(“FreqList” & Number)
    
                        Dim ParamFrequencyID As SqlParameter = DBCommand.Parameters.Add("@nFrequencyID", SqlDbType.Int)
                        ParamFrequencyID.Value = Freq.SelectedIndex
                        ParamFrequencyID.Direction = ParameterDirection.Input
    
                        DBCommand.ExecuteNonQuery()
                        DBCommand.Parameters.Clear()
                    End If
                End If
            Next
    
            DBConnection.Close()