top of page

COMBOBOX C# Y SQL SERVER 

Código simple para cargar un ComboBox en C# a partir de una consulta SQL.

using System;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace ResumenDeMacros
 

        public void CargarCombo(ComboBox elCombo)
        {

          //Definir coneccion SQL
            SqlConnection con = new SqlConnection(@"Data Source=miServer ;" +
      "user id = miid; password = mipw;Initial Catalog=EMPRESA;Integrated Security=true;");
            string textoCmd = "SELECT [NICK] FROM[empresa].[dbo].[View_Inmuebles]";

            try
            {

                 //Abrir coneccion
             
  con.Open();

                //Ejecutar sentencia SQL
                SqlCommand cmd = new SqlCommand(textoCmd, con);
                SqlDataReader reader = cmd.ExecuteReader();

                if (reader.HasRows)
                {
               
    while (reader.Read())
                    {

                         //Agrear información al combo
                        elCombo.Items.Add(reader["Nick"].ToString());   //elCombo.Items.Add(reader.GetString(0));   tambien funciona

                                                                                      //elCombo.Items.Add(reader[0].ToString()); tambien funciona
                    }
                }
             
  con.Close();
            }
            catch (Exception e)
            {

             
  MessageBox.Show(e.Message);
            }
        }
    

bottom of page