Query Sql to show it in a DropDownList

0

I want to make a selection list by means of a DropDownList but it does not generate anything, I do not know if I have any errors

    Protected Sub DropDownList4_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownList4.SelectedIndexChanged
    Dim conexion As New Conexion
    Dim conn As SqlConnection = conexion.conectar()
    Dim cmd As New SqlCommand("SELECT (tipo_doc) FROM TipoDocumento", conn)
    cmd.CommandType = CommandType.Text
    cmd.Connection = conn
    conn.Open()
    DropDownList4.DataSource = cmd.ExecuteReader()
    DropDownList4.DataTextField = "tipo_doc"
    DropDownList4.DataBind()
    conn.Close()
End Sub
    
asked by Angie Aroca 29.10.2018 в 16:55
source

1 answer

0

If you are sure that your table has records ...

Private Sub CargarDropDownList4()
Try
    Dim connString As String = "Server=Myserver;Database=MiDb;Trusted_Connection=True"
    Dim Conn As New SqlConnection(connString)
    Conn.Open()
    Dim da As New SqlDataAdapter("SELECT tipo_doc FROM TipoDocumento", Conn)
    Dim dt As New DataTable
    da.Fill(dt)
    'Sirve para recuperar la selccion: DropDownList4.SelectedValue
    DropDownList4.ValueMember = "tipo_doc"
    'Sirve para que el usuario pueda ver las opcciones disponibles
    DropDownList4.DisplayMember = "tipo_doc"
    DropDownList4.DataSource = dt

    Conn.Close()
Catch ex As Exception
    MessageBox.Show("Problemas:" & ex.Message)
End Try

End Sub

You are uploading your information in the DropDownList4_SelectedIndexChanged event, so every time you change the selection, you reload the information (I do not know what environment you are working with, whether it is Windows Form or web). You must upload the information once. for example:

Private Sub MiFormulario_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
   CargarDropDownList4()
End Sub

Greetings

    
answered by 29.10.2018 в 19:03