VB.Net Dropdownlist值始终为1

时间:2016-07-18 07:54:46

标签: asp.net vb.net

我从数据库中填写了一个Dropdownlist,使用数据库中的ID作为ValueField,但它不起作用

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim strConnection As String = "DEMOString"
    connection = New OleDbConnection(strConnection)
    connection.ConnectionString = strConnection
    connection.Open()

    Dim dtb As DataTable

    Dim strSql As String = "SELECT * FROM Personen"
    dtb = New DataTable()
    Using dad As New OleDbDataAdapter(strSql, connection)
        dad.Fill(dtb)
    End Using

    dtb.Columns.Add("Fullname", GetType(String), "Vorname + ' ' + Nachname")
    ddlName.Items.Clear()
    ddlName.DataSource = dtb
    ddlName.DataTextField = "Fullname"
    ddlName.DataValueField = "sozNr"
    ddlName.DataBind()

    connection.Close()
End Sub

当我尝试使用ddlName.SelectedItem.Value时,我会为每个项目获得1。

使用代码

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim dateString As String = tbDate.Text
    Dim name As String = ddlName.SelectedItem.Text
    Dim des As String = tbDescription.Text
    MsgBox(ddlName.SelectedItem.Value)

1 个答案:

答案 0 :(得分:2)

如果启用了viewstate(默认),则每次回发都不需要DataBind DropDownList。这将覆盖SelectedIndex之类的所有更改。而是将Page_Load中的代码放入Not Is PostBack支票:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not Page.IsPostBack Then
        Dim strConnection As String = "DEMOString"
        connection = New OleDbConnection(strConnection)
        connection.ConnectionString = strConnection
        connection.Open()

        Dim strSql As String = "SELECT * FROM Personen"
        Dim dtb As New DataTable()
        Using dad As New OleDbDataAdapter(strSql, connection)
            dad.Fill(dtb)
        End Using

        dtb.Columns.Add("Fullname", GetType(String), "Vorname + ' ' + Nachname")
        ddlName.DataSource = dtb
        ddlName.DataTextField = "Fullname"
        ddlName.DataValueField = "sozNr"
        ddlName.DataBind()

        connection.Close()
    End If
End Sub

Side-Note:您也不应该重用连接。而是在您使用它的方法中创建,初始化和关闭它,最好使用Using - 语句,这也可以确保在发生错误时处理/关闭它。