OnSelectedIndexChange from a DropDownList not working

Hyuga

Freshman
Joined
Jul 21, 2005
Messages
30
Hello again. It seems I only have problems...well, that's true

My last one, from a aspx page the users clicks on a link and a new window opens containing a form. This form has some DropDownLists and some other controls, and I have to populate these lists. Some of them can (and should) be populated on Page Load, but some others depends on the value from some of the populated_on_load DropDownLists.

This should not be a problem. I set the OnSelectedIndexChange event of the "prepopulated" list to wire the event to a sub, and from the sub, I populate the rest. Simple, but it is not working. And i don't know why.

The code from the server side:
Visual Basic:
    public empleado as String
    private query As String

    Sub Page_Load(sender As Object, e As EventArgs)
         Dim Conexion As OleDbConnection = New OleDbConnection(strConexion)
         Dim i As Integer

         If Not IsPostBack Then
             empleado = Request.QueryString("cod")
             If empleado <> "" Then
                     usuarioApertura.Text = empleado

                     'Cargamos las entidades
                     query = "SELECT CodigoEntidad FROM TCodigosEntidades"
                     Dim da As New OleDbDataAdapter(query, Conexion)
                     Dim ds As New DataSet
                     da.Fill(ds, "CodigoEntidad")
                     'Asociamos los datos necesarios al DataGrid
                     With codigoEntidad
                         .DataTextField = "CodigoEntidad"
                         .DataValueField = "CodigoEntidad"
                         .DataSource = ds
                         .DataBind()
                     End With
             End If
         End If
    End Sub

    Sub CargarTareas(sender As Object, e As System.EventArgs)
         Dim MsgBoxText As String = "Populating DropdownLists"
         MsgBox(MsgBoxText)
    End Sub

The HTML code in the next post, I have some weird errors posting.....
 
And the HTML code, as promised:
Visual Basic:
    <form runat="server">
            <div><asp:Label id="labelUsuarioApertura" runat="server">Usuario de Apertura: </asp:Label>
                <asp:Label id="usuarioApertura" runat="server"></asp:Label>
            </div>
            <div><asp:Label id="labelCodigoEntidad" runat="server">Entidad: </asp:Label>
                <DropDownList id="codigoEntidad" onSelectedIndexChange="CargarTareas" AutoPostBack="True" runat="server"></DropDownList>
            </div>
   </form>

The Sub CargarTareas is never reached, the Request.Params("__EVENTTARGET") has the correct object who has fired the OnClick event but the sub is not reached.

Any idea?

NOTE: I have changed the asp:_ DropDownList for DropDownList because of the board smilie convertor, it has been translated to this when posted:
<asp<img src="images/smilies/biggrin.gif" border="0" alt="" title="Big Grin" class="inlineimg" />ropDownList :rolleyes:
 
kahlua001 said:
Dont use MsgBox, use a response.write or use javascript for a prompt box.

Hi Kahlua001!

I'm not using MsgBox, I'm using the response.write/javascript combination to pop up the messages, but to shorten the code posted, I've used the MsgBox function.
 
Bind your handler in codebehind, not as an attribute.

Sub CargarTareas(ByVal sender As Object, ByVal e As System.EventArgs) Handles codigoEntidad.SelectedIndexChanged
 
hrabia said:
Bind your handler in codebehind, not as an attribute.

Sub CargarTareas(ByVal sender As Object, ByVal e As System.EventArgs) Handles codigoEntidad.SelectedIndexChanged

Yesterday I have tried it, but when I try to use the "Handles", the compiler told me that it needs a WithEvents clause. I'll try again using codebehind (I'm writing my server-side code "inline")
 
Something strange was happening, when I try to load the page, the compiler tell me that the selectedindexchange event cannot be found.
The dropdown is declared like this in the .aspx:
<asp:DropDownList id="codigoEntidad" runat="server" AutoPostBack="True" OnSelectedIndexChange="CargarTareas"></asp:DropDownList>

And in codebehind, I declare the control like this:
Visual Basic:
Protected WithEvents codigoEntidad As System.Web.UI.WebControls.DropDownList

And the event handler like this:
Visual Basic:
Sub CargarTareas(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles codigoEntidad.SelectedIndexChange
 
Here I post the complete code of my page, to see if anybody can help me:
Visual Basic:
<%@ Page Language="VB" EnableViewState="True"  %>
<%@ import Namespace="System.Data" %>
<%@ import Namespace="System.Data.OleDb" %>
<script  runat="server">
    public empleado as String

    private strConexion As String = "PROVIDER=MICROSOFT.JET.OLEDB.4.0;DATA SOURCE=" & ConfigurationSettings.AppSettings("BDTI")
    private query As String

    Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
         Dim Conexion As OleDbConnection = New OleDbConnection(strConexion)
         Dim ConexionExiste As OleDbConnection = New OleDbConnection(strConexion)
         Dim i As Integer

         ' Buscamos el codigo de empleado, si se ha pasado y si existe en la base de datos
         If Not IsPostBack Then
             empleado = "10251651"
             If empleado <> "" Then
                 Dim strSQLExiste as String = "SELECT CodigoEmpleado FROM Personas WHERE CodigoEmpleado LIKE '" + empleado + "'"
                 Dim SQLExiste as New OleDbCommand(strSQLExiste, ConexionExiste)

                 ConexionExiste.Open()
                 Dim drExiste as OleDbDataReader = SQLExiste.ExecuteReader()
                 If drExiste.hasRows Then
                     usuarioApertura.Text = empleado

                     'Cargamos las entidades
                     query = "SELECT CodigoEntidad FROM TCodigosEntidades"
                     Dim da As New OleDbDataAdapter(query, Conexion)
                     Dim ds As New DataSet
                     da.Fill(ds, "CodigoEntidad")
                     'Asociamos los datos necesarios al DataGrid
                     With codigoEntidad
                        .selectedindex = 1
                         .DataTextField = "CodigoEntidad"
                         .DataValueField = "CodigoEntidad"
                         .DataSource = ds
                         .DataBind()
                     End With

                 Else
                     MuestraAlerta("Debe indicarse un Codigo de Empleado válido")
                 End If
                 ConexionExiste.Close()
             Else
                 MuestraAlerta("Debe indicarse un Codigo de Empleado")
             End If
        Else
        usuarioApertura.text="kestapasando"
         End If
    End Sub

    Sub MuestraAlerta(MsgBoxText As String)
         Response.Write("<script language='JavaScript'>")
         Response.Write("alert('" & MsgBoxText & "');")
         Response.Write("<" & "/script>")
         Response.Write("<script>var win = window.self;win.opener=window.self;win.close();<" + "/script>")
    End Sub

    Sub CargarTareas(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim Conexion As OleDbConnection = New OleDbConnection(strConexion)
        Dim MsgBoxText As String = "comor" 'codigoEntidad.SelectedItem.Value
        Response.Write("<script language='JavaScript'>")
        Response.Write("alert('" & MsgBoxText & "');")
        Response.Write("<" & "/script>")
        Response.Write("<script>var win = window.self;win.opener=window.self;win.close();<" + "/script>")
        'Cargamos tipos de tareas
        query = "SELECT CodigoTipoTarea, DescripcionTipoTarea FROM TCodigosTipoTarea WHERE CodigoEntidad LIKE '" + codigoEntidad.SelectedItem.Value + "'"
        Dim da As New OleDbDataAdapter(query, Conexion)
        Dim ds As New DataSet
        da.Fill(ds, "TipoTarea")
        'Asociamos los datos necesarios al Dropdownlist
        With tipoTarea
            .DataTextField = "DescripcionTipoTarea"
            .DataValueField = "CodigoTipoTarea"
            .DataSource = ds
            .DataBind()
        End With
    End Sub
</script>
<html>
<head>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Panel id="Panel1" runat="server" Width="100%">
            <div><asp:Label id="labelUsuarioApertura" runat="server">Usuario de Apertura: </asp:Label><asp:Label id="usuarioApertura" runat="server"></asp:Label>
            </div>
            <div><asp:Label id="labelCodigoEntidad" runat="server">Entidad: </asp:Label>
                <asp: DropDownList id="codigoEntidad" runat="server" AutoPostBack="True" OnSelectedIndexChange="CargarTareas"></asp: DropDownList>
            </div>
            <div><asp:Label id="labelTipoTarea" runat="server">Tipo de Tarea: </asp:Label>
                <asp: DropDownList id="tipoTarea" runat="server"></asp: DropDownList>
            </div>
            <div><asp:Label id="labelTipoSubtarea" runat="server">Tipo de Subtarea: </asp:Label>
                <asp: DropDownList id="tipoSubtarea" runat="server"></asp: DropDownList>
            </div>
        </asp:Panel>
    </form>
</body>
</html>

NOTE: Space included between asp and DropDownList to avoid the smilie conversion
 
Ok, I've found a solution, but I don't know why I have the problem I solved now.

Searching through the net trying to find a solution, I reached this page:
http://support.microsoft.com/default.aspx?scid=kb;en-us;314809

In one of the paragraphs, you can read that:
When ASP.NET renders the page to the browser, the controls that are created dynamically do not have an associated Change event. Because no event is present, ASP.NET does not save the view state. This is called View State Optimization.

So I have tried the solution to this, thinking that this will solve my problem. And it does. Below you can see what have I added to my code.

In Page_Load()
Visual Basic:
AddHandler CType(Page.FindControl("codigoEntidad"), DropDownList).SelectedIndexChanged, AddressOf CargarTareas

This does the trick. But I don't know why the previous code is not binding correctly the event to my handler, my control is not dinamically created.
 
Back
Top