Avatar of taduh
taduhFlag for United States of America asked on

Want to programmatically set a dropdownlist selected value to a saved value - with a twist

Hi Experts,

I want to programatically set a DDL's selected value to a value I have saved in a variable. For instance, if the selected value was "Cincinnati", I have, in the past, saved it to a string variable, say SvCity, then at a later point in the program (when the Selected Value could have changed) I reset it to "Cincinnati" using DDL.SelectedValue = SvCity.  

Here's the twist though - This is a dynamic drop-down list populated from an SQL table that could be changing. "Cincinnati" may noy even be in the list when I go back, so I need to check to see if the DDL contains "Cincinnati" before I try to set the Selected Value to it.

Now, I'm trying to use the Contains parameter of the DDL to see if it contains the saved value, but in order to do so, I have to make the variable in which I save the value a ListItem. The problem is that I'm getting a syntax error when I try to set that variable equal to a string or  a textbox value or even to DDL.SelectedValue.

Is there a way around this? Is there a better way to do this?

Thanks,

taDUH
.NET ProgrammingVisual Basic ClassicASP.NET

Avatar of undefined
Last Comment
taduh

8/22/2022 - Mon
daveamour

Do you need to check if it's in the list as if you try and set it to be selecetd and it's not in the list then you get a runtime Exception?
If so then a quick fix would be just to wrap your code in a try catch block.
 
daveamour

You can also do this:

<asp:DropDownList ID="People" runat="server">
<asp:ListItem Value="Dave"></asp:ListItem>
<asp:ListItem Value="Fred"></asp:ListItem>
<asp:ListItem Value="Sarah"></asp:ListItem>
<asp:ListItem Value="Tracey"></asp:ListItem>
</asp:DropDownList>

string personName = "Dave";

Response.Write(People.Items.Contains(new ListItem(personName)));
Anurag Thakur

you can very well do that the only thing is what you have pointed out is that whether the value exists or not

this is how it can be done and you can deo it be text of the ddl or the value of the ddl

if(ddldemotime.Items.FindByValue("Valuehere")!=null)
  ddldemotime.Items.FindByValue("Valuehere").Selected = true;  

or

if(ddldemotime.Items.FindByText("Valuehere")!=null)
  ddldemotime.Items.FindByText("Valuehere").Selected = true;  
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
ASKER
taduh

daveamour,

I tried your suggestion, but can't get the Items.Contains property to recognize that the itemm is indeed in the dropdown list. In the attached code examle CurrOBXValue is the variable where I save the selected value. It contains the value that I want to check to see if it is still in the dropdown list. Take a look at my code and see if you have any suggestions.
Else
                Inlist = False
                Try
                    Inlist = dropdownCustXBanks.Items.Contains(New ListItem(CurrOBXValue))
 
                Catch ex As Exception
 
 
                End Try
 
                If Inlist = True Then
                    dropdownCustXBanks.SelectedValue = CurrOBXValue
                End If

Open in new window

daveamour

Have you debugged?  I would remove the try catch as you don't need it and also there could be an exception happening which you are missing!
So remove the try catch and debug it and see for sure if Inlist is true or false.
Let me know how that goes?
Alos beware of Case - capitals will matter so it must be an exact match!
ASKER
taduh

ragi0017,

My version of Visual Basic does not support testing for null. It says to use System.DBNull, but when I use that, it does not like that either.

taduh
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
ASKER
taduh

daveamour,

I got rid of the Try/Catch and just did the following, but it still does not detect the value in the list.

See attached code.
 Else
                Inlist = False
                Inlist = dropdownCustXBanks.Items.Contains(New ListItem(CurrOBXValue))
                If Inlist = True Then
                    dropdownCustXBanks.SelectedValue = CurrOBXValue
                End If

Open in new window

daveamour

Do you know how to debug your code using the Visual studio Debugger?
ASKER
taduh

Somewhat - you mean as far as setting watches and stepping through the code ,etc.?

That's what I've been doing is stepping through the code and watching it fail to set Inlist to True when it executes the "contains" statement.

Is there something else I can be doing in debug mode?
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
daveamour

Yes  - you can look at the dropdownCustXBanks.Items colledction at the same time and see whats actually in there at that point in time.
Anurag Thakur

try comparing it with Nothing instead of null
ASKER
taduh

Okay, that was a good idea. It helped me to see that I was looking to see if the list contained the item.text rather than the value...so I changed my code to see if the list contained the value. See attached code.

In the statement:

Inlist = dropdownCustXBanks.Items.Contains(New ListItem(CurrOBXTRN))

CurrOBXTRN has a squiggly line under it indicating it is being referenced before it has been assigned a value, but I assure you that is not the case because if you cursor over CurrOBXTRN 2 lines later, you will see the value. It also shows up in the watch list.

This has to have something to do with why its not recognizing that the value is in the list.


Else
                Inlist = False
                Inlist = dropdownCustXBanks.Items.Contains(New ListItem(CurrOBXTRN))
                If Inlist = True Then
                    dropdownCustXBanks.SelectedValue = CurrOBXTRN
                End If
             

Open in new window

Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
daveamour

Hmm weird, not sure whats occurring then!?
ASKER
taduh

ragi0017,

I'm having the same issue if I use your statement that I'm having with daveamour's solution - CurrOBXTRN has a squiggly line under it and when I cursor over it, I get the following message:

"Value 'CurrOBXTRN' is used before it has been assigned a value",

but it has clearly been assigned a value because it shows that value in my watch list when I execute the code.

Any Ideas?
ASKER
taduh

daveamour:

Okay, I got past the squiggly line problem - I had to initialize CurrOBXTRN to a value in the Dim statement, but I still cannot get the attached code to return an Inlist = True.

Any other ideas?
Inlist = False
                Inlist = dropdownCustXBanks.Items.Contains(New ListItem(CurrOBXTRN))
                If Inlist = True Then
                    dropdownCustXBanks.SelectedValue = CurrOBXTRN
                End If

Open in new window

All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
Anurag Thakur

its correct - the error message is saying before you use the variable you have to assign it a value
what is the scope of CurrOBXTRN i.e. where is it declared and where is it initialized
ASKER
taduh

its declared at the top of the subroutine that the "contains" statement is in, but it was being assigned a value conditionally. That may have been the problem, however I still fail to see why the "contains" statement is not recognizing that CurrOBXTRN is in the dropdownlist.
daveamour

Hmm dunno but I suspect something silly that is being overlooked.  Don't take anythign forgranted, double check everythingm check spelling, case, spaces etc.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
ASKER
taduh

daveamour, ragi0017

Would you care to see the whole subroutine?

It's attached.

Sub Refresh_CustXBanksDDL_From_Table(ByRef OBXFunction As String)
        'This subroutine re-initializes the Order Bank Exclusions from the SQL view
 
        Dim HasOBX As Boolean
        Dim NumOBX As Integer
        'Mark the current selection in the DDL
        Dim CurrOBXValue As String = "- Select Bank -"
        Dim CurrOBXTRN As String = "0"
 
        Dim Inlist As Boolean = False
 
        If OBXFunction = "Add" Then
            CurrOBXTRN = txtboxExclTRN.Text
            CurrOBXValue = txtboxExclBank.Text
        ElseIf OBXFunction = "Del" Or DropDownOrderNum.Text <> txtboxOrderNum.Text Then
            CurrOBXTRN = "0"
            CurrOBXValue = "- Select Bank -"
        ElseIf dropdownCustXBanks.SelectedValue.ToString <> "" Then
            CurrOBXTRN = dropdownCustXBanks.SelectedValue
            CurrOBXValue = dropdownCustXBanks.SelectedItem.Text
        End If
 
 
        'Identify the current number of banks in the Order Bank Exclusion dropdown. Subtract 1 to 
        'exclude the "- Select Bank -" entry.
        Dim DDLOrderExcls As Integer
        DDLOrderExcls = dropdownCustXBanks.Items.Count - 1
 
 
        'Clear the drop down list
        dropdownCustXBanks.Items.Clear()
 
        'Check the SQL table for exclusions for the current order
        Call Check_For_Order_Exclusions(HasOBX, NumOBX)
 
        'If there are exclusions in the Order Bank Exclusion Table...
        If NumOBX > 0 Then
            dropdownCustXBanks.Items.Insert(0, "- Select Bank -")
            dropdownCustXBanks.SelectedValue = "- Select Bank -"
            dropdownCustXBanks.SelectedIndex = 0
            dropdownCustXBanks.DataBind()
            If CurrOBXValue = "- Select Bank -" Then
                dropdownCustXBanks.SelectedValue = "- Select Bank -"
                dropdownCustXBanks.SelectedIndex = 0
                'Sets the selected item to the saved selection.
                'ElseIf dropdownCustXBanks.Items.Contains(New ListItem(CurrOBXValue)) Then
            Else
                Inlist = dropdownCustXBanks.Items.Contains(New ListItem(CurrOBXTRN))
                If Inlist = True Then
                    dropdownCustXBanks.SelectedValue = CurrOBXTRN
                End If
                'Otherwise, if there are no exclusions in the Order Exclusion table either, simply 
                'populate the DDL with the "- Select Bank -" entry and make it the current selection.
            End If
        Else
                dropdownCustXBanks.Items.Insert(0, "- Select Bank -")
                dropdownCustXBanks.SelectedValue = "- Select Bank -"
                dropdownCustXBanks.SelectedIndex = 0
        End If
 
 
    End Sub

Open in new window

ASKER CERTIFIED SOLUTION
taduh

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
SOLUTION
Log in to continue reading
Log In
Sign up - Free for 7 days
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
ASKER
taduh

ragi0017,

I can't accept that solution because

ddldemotime.Items.FindByValue(CurrOBXTRN).Selected = true;  

did not set dropdownCustXBanks.SelectedValue = the value stored in CurrOBXTRN.

The only solution I can accept is the one I posted because it will set dropdownCustXBanks.SelectedValue = the value stored in CurrOBXTRN.

Not trying to make you jump through hoops, just trying to get a workable solution posted.