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);
	MyRepeater.DataBind();
}

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

Comments

Marek 12 Oct 2006

Hi,

I just wonder how you will recognize in which repeater’s row the dropdown list index has been changed?

Cheers,
Marek

Helen 12 Oct 2006

The dropdownlist will be passed to the SelectedIndexChange event as the “object sender” parameter. Once you cast it into a DropDownList type you can look at the Parent property to get a reference back to the repeater row.

DropDownList dropdown = (DropDownList) sender;

James 24 Feb 2010

Ha! I have been wondering for a day and a half how to get a value from another control in the dropdown’s row, thanks Helen.

Chris West 10 May 2011

Hi

I’ve used an online tool to convert the code to VB but when I put it into my project it generates an error.

It doesn’t like me trying to access the events in this way: MyRepeater.ItemDataBound
MyList.SelectedIndexChanged

It’s possible that the convert tool is not providing a working conversion. Do you have a VB version of this solution?

Thanks

Chris.

helen 30 May 2011

You need to use AddHandler (http://msdn.microsoft.com/en-us/library/6yyk8z93%28v=vs.71%29.aspx) to wire up the events in code using VB.