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







Comments
Hi,
I just wonder how you will recognize in which repeater’s row the dropdown list index has been changed?
Cheers,
Marek
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;
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.
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.
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.