Why SelectedIndexChanged fires for a DropDownList when a button is clicked?
I have an ASP.NET DropDownList
with AutoPostBack=true
and EnableViewState=false
. I have a button on the page that does nothing. If I change the selection in the ddl, it posts back , which is expected. If I click the button, the page posts back and the ddl's Selecte开发者_StackOverflowdIndexChanged
fires. Why does it get fired?
Feedback from Microsoft :- http://connect.microsoft.com/VisualStudio/feedback/details/103844/dropdownlist-always-fire-selectedindexchanged-event-when-viewstate-is-disabled-and-the-selected-item-is-not-changed-by-the-user
"Thanks for your feedback. If ViewState is disabled on the page or on the DropDownList control, the selected index cannot be saved, so each postback looks like the selected index has been changed. You can save the selected index yourself and compare against it to see if the selection has really changed, or you can enable ViewState on the DropDownList. "
In your case the viewstate of the dropdownlist is false. Enable the same or you can compare index of the selected item as suggested above.
Try enabling viewstate. This is a common issue.
EDIT
If you don't want to enable viewstate you'll have to track the drop list value yourself, like this guy did DropDownList OnSelectedIndexChange to 0th index w/out ViewState
If you load your ddl in page_load, when you click the button it goes page_load again and it loads ddl items again that changes selected index. But I don't know your code, so this is an assumption.
I had the same issue. I found my problem was that I called my Render function Page_Load
.
Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.PreRender
I completely missed the fact that the page loaded Page_Load
as a default load function, then loaded it again when it ran prerender. I changed it to the following, and now the function is only called once:
Sub Renderer(ByVal sender As Object, ByVal e As EventArgs) Handles Me.PreRender
精彩评论