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" "">

<html xmlns="" >

<head runat="server">




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


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






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


End If

End Sub

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


End Sub

End Class

blog comments powered by Disqus