ASP.NET DropDownList First Item Won't Fire OnIndexChanged Explanation and Fix

Hi all! haven't post anything lately because now I'm quite busy. Today's post is a very technical one based on the problem I encounter during my work. So I found a problem that is quite common in ASP, which is the first item in ASP dropdownlist won't fire OnIndexChanged. I'd said it's quite common because I found many cases when I googled it. The solution offered is quite simple, which is adding a dummy first element before anything else. Just add this:

<asp:ListItem Value="" Text="" Enabled=false />

in your ASP dropdownlist and the problem solved. But I really curious what is the cause of this problem, and based on my analysis, here's why:
  1. When the dropdownlist changed, because you set the AutoPostBack value to true, the ASP cycle begun, and it goes like this : OnInit-LoadViewState-PageLoad-OnIndexChanged
  2. Somehow, your dropdownlist value is changed to default when the postback happen, which is index 0 (first item). So, what actually happen is, when the form load its ViewState, it didn't detect any index changes (from 0 because of the reset to 0)
So, adding up a dummy item will surely fix your problem, because when the postback happen, your dropdownlist value will changed to that dummy item (index 0), and because your first item now placed at index 1, it will fires OnIndexChanged.

The other workaround I found is set your dropdownlist index on OnInit. Because you set it on OnInit, your dropdownlist selectedIndex will changed to the current value just before the LoadViewState happened so the changes between index is detected.

Third workaround is find a way to retain your dropdownlist value after postback, which I fail to find.

Sorry if I didn't explain it properly. This problem is very technical so it's quite hard to explain it. If you have any question or anything to discuss, feel free to email me.

Hope it helps :v

Comments