Rellenar un ComboBox con un DataReader

2546 vistas

Veamos cómo rellenar un ComboBox con un DataReader:



vbnet
  1. Imports System
  2. Imports System.Data
  3. Imports System.Data.SqlClient
  4. Imports System.Windows.Forms
  5.  
  6. ' ...
  7. Dim con As SqlConnection = Nothing
  8. Dim command As SqlCommand = Nothing
  9. Dim cs As String = "cadena de conexión SQL"
  10. Dim dr As SqlDataReader = Nothing
  11.  
  12. Try
  13.   con = New SqlConnection(cs)
  14.   command = New SqlCommand("SELECT campo FROM Tabla",con)
  15.  
  16.   ' abrir la conexión
  17.   con.Open()
  18.   dr = command.ExecuteReader()
  19.  
  20.   ' vaciar ComboBox
  21.   ComboBox1.Items.Clear()
  22.  
  23.   If dr.HasRows Then
  24.     While dr.Read
  25.       ComboBox1.Items.Add(dr.GetValue(0))
  26.     End While
  27.   Else
  28.     MessageBox.Show("No result for your Data", "Infos",
  29. MessageBoxButtons.OK, MessageBoxIcon.Information)
  30.   End If
  31. Catch ex As Exception
  32.   MessageBox.Show(ex.Message)
  33. Finally
  34.   If Not (dr Is Nothing) Then dr.Close()
  35.   If Not (con Is Nothing) Then con.Close()
  36. End Try
  37.  
  38. ' ...