Rellenar un ComboBox con un DataReader

2140 vistas

El siguiente código permite rellenar de forma rápida un control ComboBox (ComboBox1) con un DataReader.



csharp
  1. using System;
  2. using System.Data;
  3. using System.Data.SqlClient;
  4. using System.Windows.Forms;
  5.  
  6. //...
  7. SqlConnection con = null;
  8. SqlCommand command = null;
  9. String cs = "cadena de conexión SQL";
  10. SqlDataReader dr = null;
  11.  
  12. try
  13. {
  14.   con = new SqlConnection(cs);
  15.   command = new SqlCommand("SELECT campo FROM Tabla", con);
  16.   con.Open();
  17.   dr = command.ExecuteReader();
  18.  
  19.   ComboBox1.Items.Clear();
  20.  
  21.   if(dr.HasRows)
  22.   {
  23.     while(dr.Read())
  24.     { ComboBox1.Items.Add(dr.GetValue(0));}
  25.   }
  26.   else
  27.   { MessageBox.Show("No result for your Data", "Infos",
  28. MessageBoxButtons.OK, MessageBoxIcon.Information);}
  29. }
  30. catch(Exception ex)
  31. { MessageBox.Show(ex.Message);}
  32. finally
  33. {
  34.   if(dr != null) {dr.Close();}
  35.   if(con != null) {con.Close();}
  36. }