Sorx
Sorx

Reputation: 23

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

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.

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)

Upvotes: 0

Views: 78

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460168

You don't have to DataBind the DropDownList on every postback if viewstate is enabled(default). That will overwrite all changes like the SelectedIndex. Instead put the code in Page_Load in a Not Is PostBack check:

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.

Upvotes: 2

Related Questions