Link to home
Start Free TrialLog in
Avatar of cdemott33
cdemott33Flag for United States of America

asked on

Help with Try... Catch and the Selected Value of a DropDownList

Hi Experts - I need help using the Try... catch block with my DropDownList Control.

The value of the drop down have recently changed and may no longer match the values in my database.  That being the case i wanted to set the SelectedValue for any non-matched items to the default value of "Unassigned".  Here's what I wrote:

'  Get the values for the dropdownlist
' -------------------------------------------------------------------------------
Dim MyBLL As New PickPackBLL()
Dim dt As DataTable = MyBLL.GetBinLocs()

ddOpp.DataSource = dt
ddOpp.DataTextField = "BinLoc"
ddOpp.DataValueField = "BinLoc"

'  Set the Selected Value of the drop down list.
' -------------------------------------------------------------------------------
Dim SelectedBinLoc As String
Dim defaultSelectedIndex As String = "Unassigned"

Dim pickTicketLogic As New PickPackItemsBLL()
Dim dtpick As DataTable = pickTicketLogic.GetPickTicketItems(hfPickTicketID.Value)

If dtpick.Rows.Count > 0 Then
    Dim row As DataRow = dtpick.Rows(0)
    SelectedBinLoc = row("BinLoc")
End If

Try
    ddOpp.SelectedValue = SelectedBinLoc
Catch ex As Exception
    ddOpp.SelectedValue = defaultSelectedIndex
End Try

ddOpp.DataBind()

Open in new window


Even with the "Try" block in place I'm still getting the "'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items."

I was hoping that the try would catch that error and the move on to the exception block and useing the defaultSelectedIndex value.

Can you tell me what I'm doing wrong?

Thanks!
SOLUTION
Avatar of Miguel Oz
Miguel Oz
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of cdemott33

ASKER

Thanks everyone for your help.  I had two problems.  One was the use of the try block. and the other was the databind.  Once I moved the databind above the code where I set the SelectedValue everything worked.

Thanks again!