在页面加载事件上填充下拉列表

时间:2011-04-15 04:27:23

标签: asp.net sql vb.net

我不明白为什么这不起作用。

我有一个名为ddlRoomName的下拉列表和一个名为roomlist的SQL表。

当我在SQL编辑器中运行SQL命令时,它工作正常。但是当我加载页面时,房间不会加载!

我错过了一些明显的东西吗?

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

        ddlRoomName.Items.Clear()
        ddlRoomName.Items.Add(New ListItem("--Select Room--", ""))
        ddlRoomName.AppendDataBoundItems = True

        Dim strConnString As String = ConfigurationManager.ConnectionStrings("a_cisco").ConnectionString
        Dim strQuery As String = "Select * from roomlist"
        Dim con As New SqlConnection(strConnString)
        Dim cmd As New SqlCommand()

        cmd.CommandType = CommandType.Text
        cmd.CommandText = strQuery
        cmd.Connection = con

        Try
            con.Open()
            ddlRoomName.DataSource = cmd.ExecuteReader()
            ddlRoomName.DataTextField = "RoomName"
            ddlRoomName.DataValueField = "intRoom"
            ddlRoomName.DataBind()

        Catch ex As Exception
            Throw ex
        Finally
            con.Close()

        End Try
    End If
End Sub

1 个答案:

答案 0 :(得分:1)

您只是在回发时加载它们。这真的是你想要的吗?也许你想要:

If Not Page.IsPostBack Then

End If

(然后ViewState会将DropDownList中的项目保留在回发中