Sunday, October 26, 2008

Detect DropDownList SelectedIndexChanged on Page Load

In ASP.NET, when you define an asp:DropDownList with AutoPostBack="true", say if you are having two ListItems of the same value, then you select the first one, and now when you select the second one, the SelectedIndexChanged event of the DropDownList will not fire since the
SelectedValue of the DropDownList has not changed. You could use Request.Form("__EVENTTARGET") in the Page_Load to solve this problem.

Here is the example:

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="TestDropDown._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></title>


</head>


<body>


<form id="form1" runat="server">


<div>



<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true">


<asp:ListItem Text="---" Value="---"></asp:ListItem>


<asp:ListItem Text="aa" Value="aa"></asp:ListItem>


<asp:ListItem Text="bb" Value="aa"></asp:ListItem>


<asp:ListItem Text="cc" Value="cc"></asp:ListItem>


</asp:DropDownList>


</div>


</form>


</body>


</html>


Partial Public Class _Default


Inherits System.Web.UI.Page


Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load


If Me.Request.Form("__EVENTTARGET") = DropDownList1.UniqueID Then


Response.Write(DropDownList1.SelectedValue)


End If


End Sub


Private Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged


Response.Write(DateTime.Now.ToString())


End Sub


End Class

blog comments powered by Disqus