简体   繁体   English

VB.Net Dropdownlist值始终为1

[英]VB.Net Dropdownlist Value is always 1

I got a Dropdownlist filled from a Database, using the ID from the Database as ValueField but it just doesn't work 我从数据库中填充了一个下拉列表,使用数据库中的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

When I try using ddlName.SelectedItem.Value later i get 1 for every Item. 当我稍后尝试使用ddlName.SelectedItem.Value时,每个项目都会得到1。

The Using Code 使用代码

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)

You don't have to DataBind the DropDownList on every postback if viewstate is enabled(default). 如果启用了viewstate,则不必在每次回发时都对DropDownList进行数据绑定(默认)。 That will overwrite all changes like the SelectedIndex . 这将覆盖所有更改,如SelectedIndex Instead put the code in Page_Load in a Not Is PostBack check: 而是将代码放入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: you should also not reuse the connection. 注意:您也不应重复使用该连接。 Instead create, initialize and close it in the method where you use it, best by using the Using -statement which also ensures that it get's disposed/closed in case of an error. 相反,最好在使用它的方法中创建,初始化和关闭它,最好使用Using -statement,这也可以确保在发生错误时将其处置/关闭。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM