Handling SelectedIndexChange for a DropDownList in a Repeater

Came across an interesting problem yesterday trying to handle the SelectedIndexChanged event for a DropDownList that was inside a Repeater.

I found a wonderful article on Databinding that gave me most the information I needed, but their method of handling events just didn’t work for me.

My first problem was that I originally did the databinding when the OnPageLoad event fired. This meant that the DropDownList wasn’t even created when the postback events were being fired.

When I moved my databinding code to the OnInit event, I still couldn’t capture my repeater’s ItemCommand event, which was supposed to be fired in response to the postback of any component within the repeater. So what I did instead was catch the ItemDataBound event, find my DropDownList and registered an SelectedIndexChanged event for it. This made me happy because I didn’t really like the idea of handling a generic ItemCommand event anyway.

protected virtual void PageInit(object sender, EventArgs e)
	MyRepeater.DataSource = DataSource;
	MyRepeater.ItemDataBound += new RepeaterItemEventHandler(RepeaterItemDataBound);

protected virtual void RepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
	DropDownList MyList = (DropDownList) e.Item.FindControl("MyListID");
	MyList.SelectedIndexChanged += new EventHandler(MyListIndexChanged);

protected virtual void MyListIndexChanged(object sender, EventArgs e)
	// handle event

Thanks to the guys from the UK MSWebdev list, whose advice helped me figure this out :)

Posted on 25 Jan 05 by Helen Emerson (last updated on 30 May 11).
Filed under ASP.NET, Javascript