日期:2014-05-18  浏览次数:20421 次

请教各位大神:两个dropdownlist联动,一个静态,一个动态,动态的事件跑偏。。。
两个下拉列表,一个是lstCls,另一个是lstSubCls
lstCls的列表项来自数据库,是静态绑定的;lstSubCls的列表项根据lstCls的点选动态改变,内容也来自数据库。
其实是很简单的,但写完后发现lstCls的第一项不起作用:加载后,选其他的列表项,lstSubCls可以联动,但选第一项的话,lstSubCls的内容就被清空。另外,选lstCls后,在lstSubCls的内容已正确填充的情况下,点选lstSubCls的列表项,事件触发的是lstCls的onselectindexchanged。

代码如下,请帮忙分析一下问题出在哪,谢谢!

HTML code

    <asp:DropDownList ID="lstCls" runat ="server" AutoPostBack ="True" Width ="200px" 
        DataSourceID="dataProductCls" DataTextField="Class" 
        DataValueField="ID"/>
    
    <br />
   
    <asp:DropDownList ID="lstSubCls" runat ="server" Width ="200" AutoPostBack ="true" />



VB.NET code

Protected Sub lstCls_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles lstCls.SelectedIndexChanged
        Dim strSelected As String = lstCls.SelectedItem.Text
        dataProductSubCls.SelectParameters.Clear()
        dataProductSubCls.SelectParameters.Add("Selected", TypeCode.String, strSelected)
        dataProductSubCls.SelectCommand = "SELECT ProductCls.Class, ProductSubCls.ID, ProductSubCls.SubClass FROM ProductSubCls " &
                                          "INNER JOIN ProductCls ON ProductSubCls.Class = ProductCls.ID " &
                                          "WHERE ProductCls.Class = @Selected"
        lstSubCls.Enabled = True
        lstSubCls.DataSourceID = "dataProductSubCls"
        lstSubCls.DataTextField = "SubClass"
        lstSubCls.DataValueField = "ID"
        lstSubCls.DataBind()
    End Sub

    Protected Sub lstSubCls_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles lstSubCls.SelectedIndexChanged
        Dim strSelected As String = lstSubCls.SelectedItem.Text
        sqlComm = New SqlCommand("SELECT Pic, Alt FROM ProductSubCls WHERE SubClass = @Selected", sqlConn)
        sqlComm.Parameters.Add("@Selected", Data.SqlDbType.NVarChar, 50)
        sqlComm.Parameters("@Selected").Value = strSelected
        Try
            sqlConn.Open()
            reader = sqlComm.ExecuteReader
            If reader.Read Then
                ...'将内容附给其他控件
            Else
                ...'执行其他代码
            End If
        Catch ex As Exception
            Response.Write (ex.Message)
        Finally
            sqlConn.Close()
        End Try
    End Sub



------解决方案--------------------
1. 选择第一项被清空很有可能是因为你第一项没有子选项造成的。
2. lstSubCls回发你会激发onselectindexchanged不知道你什么意思,onselectindexchanged是脚本?
如果你会触发lstCls_SelectedIndexChanged事件那朔岷你的lstCls数据绑定代码有问题。
------解决方案--------------------
应该是引起了自动刷新,服务器控件吗,那样你需要再次绑定数据集,你现在第一个选择后都会重新绑定第二个combox所以,第二个总是有数的

网上有很多不刷新联动,你可以参考
------解决方案--------------------
探讨
<asp:DropDownList ID="lstSubCls" runat ="server" Width ="200" AutoPostBack ="true" />