DropDownList SelectedIndexChanged event fires twice on few Dropdowns
I have very simple aspx page & code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" EnableViewState="false">
<asp:ListItem>Item1</asp:ListItem>
<asp:ListItem>Item2</asp:ListItem>
<asp:ListItem>Item3</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" EnableViewState="false">
<asp:ListItem>Item1</asp:ListItem>
<asp:ListItem>Item2</asp:ListItem>
<asp:ListItem>Item3</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="DropDownList3" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" EnableViewState="false">
<asp:ListItem>Item1</asp:ListItem>
<asp:ListItem>Item2</asp:ListItem>
<asp:ListItem>Item3</asp:ListItem>
</asp:DropDownList>
</form>
</body>
</html>
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
usin开发者_JAVA百科g System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Write("DropDownList1_SelectedIndexChanged called! <br />");
}
}
EnableViewState="false" for all DropDown.
Could anyone explain me why DropDownList1_SelectedIndexChanged event executes twice after first dropdown value changed, then change value in second or third dropdown.
Thanks!
You disabled the viewstate for dropdowns by setting EnableViewState="false"
to them.
Take a look to a note on MSDN:
A list control must persist some values between posts to the server for this event to work correctly. Be sure that view state is enabled for the list control.
Also OnSelectedIndexChanged
event handler is the same for the each of you dropdowns: OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
.
All this means that after a postback your dropdowns think that the selected value was changed if the selected value is different from the first list item's value. That's why you've got your event handler fire twice after second postback or even thrice after third.
Just enable viewstate for dropdowns to prevent such a behaviour.
精彩评论