Solved

Setting an ASP:DropDownList.SelectedIndex

Posted on 2004-03-22
8
1,670 Views
Last Modified: 2012-06-27
I have a bound DropDownList in an ASP Webapplication for which I need to set its' SelectedIndex and/or SelectedValue property programmatically in the VB.NET code behind.

e.g.
myDDL.DataSource = myDataSource
myDDL.DataTextField = "items"
myDDL.DataValueField = "values"
DataBind()

'Where myVal is the value of an item in the DropDownList
'Selecting via SelectedIndex:
For i = 0 To myDDL.Items.Count - 1
    If myDDL.Items(i).Value = myVal Then
        myDDL.SelectedIndex = i
    End If
Next

'Selecting via SelectedValue:
myDDL.SelectedValue = myVal

Now these 2 methods do set the properties - SelectedIndex and SelectedValue, but since the control is already rendered the item for 'myVal' does not show in the control. Instead I get the first item in the controls list, as if no selection has been made.

If I move the DataBind() to after setting the SelectedIndex or SelectedValue it resets them so that nothing is selected, so again I get the first item in the DropDownList showing.

How can I select an item from the DropDownList programmatically so that it shows the item as being selected in the control?
0
Comment
Question by:Psyberion
  • 4
  • 3
8 Comments
 
LVL 6

Expert Comment

by:pillbug22
ID: 10649481
Try:

myDDL.SelectedIndex = myDDL.Items.IndexOf(myDDL.Items.FindByValue(myVal))
0
 
LVL 6

Expert Comment

by:pillbug22
ID: 10649492
Oops - didn't read all the way...

You already get it to select the item, it just needs to be bound again.

Is this DDL in a dataGrid?  If so, just put this code (or yours) inside of the _ItemDataBound event for the grid.
0
 
LVL 6

Author Comment

by:Psyberion
ID: 10649795
If I bind it again after selecting the item it still appears to have nothing selected, I'm not sure but I think the bind clears the SelectedIndex property.

The DDL is not in a datagrid no, just directly on the page.
0
 
LVL 6

Expert Comment

by:pillbug22
ID: 10649942
I just found a web app where I needed the same thing (DDL on the page), and I filled the DDL with my items, then changed the SelectedIndex property.

Are you sure it's passing a valid index/value to select?  Have you done an alert box or reponse.write to see what value it's trying to select?
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 7

Accepted Solution

by:
dante469 earned 100 total points
ID: 10650086
Psyberion,

The "'Selecting via SelectedValue" code from your snippet doesn't work since it actually changes the value (contents of myDDL.DataValueField) rather then setting the selected index value;

Would recommend something to the effect of....  This will handle item not being found as well...

Public Function setDDL(ByVal DDL As DropDownList, ByVal val As String) As Boolean
            Dim Findby As New ListItem()
            Findby = DDL.Items.FindByValue(val)
            If Findby Is Nothing Then
                DDL.SelectedIndex = 0
                Return False
            Else
                Findby.Selected = True
                Return True
            End If
        End Function

Each time you rebind the ddl the selected index is lost so you would do this after initial BIND and will NOT bind again...

ALSO and this may be a big deal!!!  If the DDL is large (more items then will display on the screen) and the selected item is off the screen (must be scrolled to see) it does not automatically scroll to become visible...  ie... 20 items in DDL, control is sized to display only 10 and the 15th has been selected...  When rendered the 15th item is selected, this can be confirmed by scrolling the DDL, but is not visible on the screen...  My work around has been to move the selected item to the first item in the DDL...  This takes it out of order, but works for my users in my environment...

Hope this answers your question and BTW I am not against bonus points :)...

Have Fun,
Dante
0
 
LVL 6

Author Comment

by:Psyberion
ID: 10665721
Dante, I'm afraid your gives me the same results as I had before. It's selecting the item (i.e. the SelectedValue holds the correct value) but it still doesn't show the selected item in the control.

I can tell this because I actually have 3 DDLs, and a selection on one of them determines what items are listed in the next. All three DDLs are only showing their first item.

e.g.: if the first list is food types {vegetables, fruit, meat} and I manually select 'fruit' the second list might then contain {banana, orange, apple}, selecting apple might give me a choice in the third DDL of {red, green} and suppose I select 'green'. Now if I made these selections programmatically my first DDL shows 'vegetables', my second DDL shows 'banana' and my third DDL shows 'red'. So the control is providing the right SelectedValue property, but it's just not showing it.

Now, the DDL is rendered in HTML as a <select> form input with <option> items. If I was doing this in PHP or just ASP I would simply render the control myself and check for when I reached the option I want, then I would simply put SELECTED in that options' tag.

If there isn't a method or property in the DDL object then it just reinforces my belief that these new languages are just dumbed down for lazy programming by wrapping everything in bulky code, and subsequently removing most of the functionality (similar to what frontpage/dreamweaver/etc. did to webpage design)....ok, grumble over.

Time to up the stakes a bit.....hmmm 100 points will do for now ;)
0
 
LVL 6

Author Comment

by:Psyberion
ID: 10665774
Btw Dante, I'll give you an extra 50 points whether you give the final solution or not, as your code snippet was rather cleaner than mine, so I'm using that now.

Ta.
0
 
LVL 6

Author Comment

by:Psyberion
ID: 10675938
Ok, reason why the DDLs were only showing their first item is because of the DataBind() statements after setting the DataSource for each DDL. Some code/pseudocode using setDDL from Dante:

DDL1.DataSource = get_ddl1_items_from_db()
DataBind()
setDDL(DDL1,my_chosen_ddl1_item)

DDL2.DataSource = get_ddl2_items_from_db(DDL1.SelectedValue) <---items in DDL2 depend on chosen item in DDL1
DataBind() <---This clears the selection on DDL1! I did not know that :(
setDDL(DDL2,my_chosen_ddl2_item)

Changing the DataBind() statements (which I now gather binds all controls on the page and not just the last one?) with DDL1.DataBind() and DDL2.DataBind() respectively, the controls now display the correctly selected items.

So, thanks Pillbug22 and Dante.

Unfortunately I didn't see anything for splitting the points, as I wanted to give Pillbug22 100points and Dante 150, but it turns out it just gave Dante the 100 points....my bad. Any idea how I can transfer some more points to you guys?
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Suggested Solutions

Normally the drop down box control found in the .Net framework tools is able to select just one data and value at a time, which is displayed on the text area.   But what if you want to have multiple values to be selected in the drop down box? As …
Recently while returning home from work my wife (another .NET developer) was murmuring something. On further poking she said that she has been assigned a task where she has to serialize and deserialize objects and she is afraid of serialization. Wha…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

707 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