C# Select and display in a combobox

Asked

Viewed 13,532 times

1

I’m creating an application in C# windows Form and wanted to know how to select a table and display a list of clients in a combobox.

  • Please give more details than you want. What you have tried and what specific question?

  • I want as Seto the values of my select done by sqlCommand in a combobox.

1 answer

2


Following this Table layout in a Database SQL Server:

inserir a descrição da imagem aqui

1 - With Datatable:

public DataTable GetUF()
{
    DataTable dataUf = new DataTable("UF");
    using (SqlConnection Connection = new SqlConnection(@"Data Source=.\SqlExpress;Initial Catalog=Db;Persist Security Info=True;User ID=sa;Password=senha"))
    using (SqlCommand Command = new SqlCommand("SELECT UFID, SIGLA FROM UF ORDER BY SIGLA", Connection))
    {
        Connection.Open();
        dataUf.Load(Command.ExecuteReader());
    }
    return dataUf;
}

Loading Datatable data to the Combobox Cmbuf

CmbUF.DropDownStyle = ComboBoxStyle.DropDownList;
CmbUF.DataSource = GetUF();
CmbUF.ValueMember = "UFID";
CmbUF.DisplayMember = "SIGLA";
CmbUF.Update();

2 - With Classe UF and Ienumerable:

Create a class that represents the data that served as a template to load the Combobox.

public class UF
{
        public int UFID { get; set; }
        public String SIGLA { get; set; }
}

Loading the data into the IEnumerable<UF>

public IEnumerable<UF> GetUF()
{
    using (SqlConnection Connection = new SqlConnection(@"Data Source=.\SqlExpress;Initial Catalog=Db;Persist Security Info=True;User ID=sa;Password=senha"))
    using (SqlCommand Command = new SqlCommand("SELECT UFID, SIGLA FROM UF ORDER BY SIGLA", Connection))
    {
        Connection.Open();
        using (SqlDataReader Reader = Command.ExecuteReader())
        {
            if (Reader.HasRows)
            {
                while (Reader.Read())
                {
                    yield return new UF()
                    {
                        UFID = Reader.GetInt32(0),
                        SIGLA = Reader.GetString(1)
                    };
                }
            }
        }
    }            
}

Loading the data from IEnumerable<UF> to the Combobox Cmbuf

CmbUF.DropDownStyle = ComboBoxStyle.DropDownList;
CmbUF.DataSource = GetUF().ToArray();
CmbUF.ValueMember = "UFID";
CmbUF.DisplayMember = "SIGLA";
CmbUF.Update();

Obs: realizes that now the GetUF() should call the ToArray(), because the Datasource needs a Ilist or Ilistsource (Arrays, Enumeration, Datatable, Dataset) to load !!!

Quick explanation of what was used in Combobox

CmbUF.DataSource = "FONTE DE DADOS (DATATABLE, DATASET, ILIST, etc)";
CmbUF.ValueMember = "NOME DO CAMPO QUE REPRESENTA A IDENTIFICAÇÃO DE CADA ITEM DO COMBOBOX";
CmbUF.DisplayMember = "TEXTO QUE SERÁ MOSTRADO NO COMBOBOX";            

var c = CmbUF.SelectedValue; //RECUPERANDO O VALOR DA UFID

Browser other questions tagged

You are not signed in. Login or sign up in order to post.