从ASP.NET下拉列表中读取数据时出错

时间:2016-03-10 06:26:57

标签: .net vb.net drop-down-menu

我正在使用.net framework 3.5更改用VB编写的代码。在这里,我必须将数据库中的一些数据绑定到下拉列表,然后读取所选值。绑定数据和读取数据的代码如下。

Public Sub setDropdown_test()
    Dim ds As New DataSet
    Dim dr As DataRow

    Try
        ds = Subject_Test.getSubjectDetails()

        dr = ds.Tables(0).NewRow()
        dr("SBJ_NAME") = "Select the subject"
        dr("SBJ_CODE") = "-1"
        ds.Tables(0).Rows.InsertAt(dr, 0)

        If ds.Tables(0).Rows.Count > 0 Then
            testDrop.DataTextField = ds.Tables(0).Columns("subject_name").Caption
            testDrop.DataValueField = ds.Tables(0).Columns("subject_code").Caption
            testDrop.DataSource = ds
            testDrop.DataBind()
        End If
    Catch ex As Exception
        'write an error here
    End Try
End Sub

Protected Sub testButton_Click(sender As Object, e As EventArgs) Handles testButton.Click
    PoupMessage("selected value is - " & testDrop.SelectedValue & " selected text is - " & testDrop.SelectedItem.ToString())
End Sub
页面中的

调用load方法setDropdown_test()。

数据绑定到下拉列表正常工作。但每次我选择一个值并单击testButton时,页面会自动重新加载并给出下拉列表第一列的输出。据我所知,停止重新加载页面是正确工作的最佳方式。但我没有那样做。
有人可以帮我解决这个问题。

1 个答案:

答案 0 :(得分:1)

由于 PostBack ,它会重置为Dropdown的第一项,这意味着每次点击按钮时,表单都会执行< em> PostBack 并重新加载表单,再次调用 setDropdown_test(),将值重置为列表中的第一个项目。

使用此语句覆盖它,以避免每次 PostBack 重新加载 DropDownList

If Not IsPostBack Then
     setDropdown_test()
End If