关于dropdownlist和listItem

关键函数,进行数据邦定操作,这里是将dropdownlist与权限点和权限名称进行绑定,编辑写在另外一个页面
    Private Sub dlTDataBind(ByVal strSql As String, ByRef dl As DropDownList)

        '数据绑定到dropdownlist控件
        Dim mySqlConnection As SqlConnection
        Dim myDatareader As SqlDataReader
        Dim myCommand As SqlCommand

        '定义选项
        Dim myItem As ListItem

        Try

            myItem = New ListItem

            mySqlConnection = New SqlConnection(ReadConStr())
            myCommand = New SqlCommand

            myCommand.Connection = mySqlConnection
            myCommand.CommandType = CommandType.Text
            myCommand.CommandText = strSql

            '打开数据库连接
            If mySqlConnection.State = ConnectionState.Open Then
                mySqlConnection.Close()
            End If
            mySqlConnection.Open()

            myDatareader = myCommand.ExecuteReader


            While myDatareader.Read()
                myItem.Text = myDatareader.Item("AuthName")
                myItem.Value = myDatareader.Item("AuthID")

                '填充dl
                dl.Items.Add(myItem)
                'dl.Items.Insert(0, myItem)
            End While

        Catch sqlEx As SqlException
            Response.Write("<script>alert('" & ReplaceSingleQuotes(sqlEx.Message) & "')</script>")
        Catch ex As Exception
            Response.Write("<script>alert('" & ReplaceSingleQuotes(ex.Message) & "')</script>")
        Finally
            If Not myDatareader.IsClosed Then
                myDatareader.Close()
            End If
            If mySqlConnection.State = ConnectionState.Open Then
                mySqlConnection.Close()
            End If

        End Try
    End Sub

 

用上面的方法添加看是没有任何问题,但是执行完成以后我们会发现,dropdownlist里面的选项是相同的,为什么会这样呢?因为在运行的时候添加的项始终是已经实例化的listitem,当添加完最后一项后,listitem的值变化成最后一项,前面添加的几项也会变化为最后的一项,并不是添加一个就完成一个,应该实例化一个添加一个用下面这种方式:

 

dlAuthIDName.Items.Insert(0, New ListItem("", "", True))

你可能感兴趣的:(list)