I'm creating an application in C # windows form and wanted to know how to do a select from a table and displayed a list of clients in a combobox.
I'm creating an application in C # windows form and wanted to know how to do a select from a table and displayed a list of clients in a combobox.
Following this table layout in a SQL Server database a>:
1-With DataTable : / p>
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 Data from the DataTable into 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 for loading the ComboBox.
public class UF
{
public int UFID { get; set; }
public String SIGLA { get; set; }
}
Loading data into 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();
Note: Note that GetUF()
should now call ToArray()
, because the DataSource needs an IList or #
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