Ken Robertson's Blog

Ramblings of a .NET developer

Odd SelectedIndexChanged behavior on DropDownLists

Been coding away on my senior project to meet our deadline for delivery in like 4 weeks and ran into this interesting problem over the weekend.

Had three drop down lists, Campus, Course, and Semester.  As one was selected, the next one was populated with the courses at the campus, and then the semesters a course was offered.

All looked good until I went to test it.  The course list would get populated, but when I selected a course, it would post back, but it was never getting to the SelectedIndexChanged method.  It was posting, it had a selected index, the event was wired up, but nothing would work.

After going through trial and error, I found that it was because I was populating the course drop down with ListItems ( dropCourse.Items.Add(new ListItem(course.Name, course.ID.ToString()); ).  If I populated it with just the straight string ( dropCourse.Items.Add(course.Name); ) then it would work.

Anyone encountered this behavior before?  I found it very odd that populating it one way would override the SelectedIndexChanged.  I filled the campus drop down with ListItems, so it must have something to do with clearing it and refilling.  I'd read some about the need to do ClearSelection(), and I was doing that, but it did no good either.

Posted: Apr 19 2004, 10:49 PM by qgyen | with 4 comment(s)
Filed under: ,

Comments

Sharad Kumar said:

Hi Ken,

I suppose you missed the fact that both times, whether postback or otherwise, you Set selected-index of drop-down-lists. You should populate DropDownLists in both case, but set selected-index only when Page.IsPostBack = false, so that during PostBack you do not over-write SelectedIndex available in PostBack Collection data.

--
Sharad

.NET Architect, eBookers.com
# April 20, 2004 2:42 AM

Ken Jackson said:

Ken,

I've had the same problem, but not because of posting back as Sharad suggests.

Solution: The event handler receives the SelectedIndex but not the SelectedValue or SelectedItem and so you have to derive the value from the index. In this example I set a session variable to the selected value of
ddReport:
[VB]
Private Sub DDreport_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DDreport.SelectedIndexChanged

Session("rpt") = DDreport.Items(DDreport.SelectedIndex).Value()

End Sub

Cheers, Ken J
# July 8, 2004 8:37 AM

Jitendra said:

Thanx a lot it help me !!

# March 1, 2008 3:53 AM

Mr.Carrot93 said:

The accused   and community support discuss the sentence presented, add, delete and   collectively arrive at a sentence. ,

# October 22, 2009 1:26 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)