Solved

Setting an ASP:DropDownList.SelectedIndex

Posted on 2004-03-22
8
1,674 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
Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

 
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
 
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

How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…
How to Install VMware Tools in Red Hat Enterprise Linux 6.4 (RHEL 6.4) Step-by-Step Tutorial

749 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