Question Using selectedItem to retrieve multiple columns in a combobox

Martinho Neves

New member
Joined
May 18, 2018
Messages
2
Programming Experience
1-3
Hello to all
I am having a bit of difficulty to find a solution to a problem.
I have a database with a table called tAno.

The structure of the table is as follows.
IdAnoAno
12010
22011
32012
42013
52014
62015
72016
82017
92018

I populate this table to a combo box like this:

cl_GestorBD gestor = new cl_GestorBD(VerifInicial.CFBDados);
string query = "SELECT * FROM tAno";

DataTable dados = gestor.EXE_READER(query);
NumRegistos = dados.Rows.Count;

Cbox_Ano.DisplayMember = "Value";
Cbox_Ano.ValueMember = "Id";

for (int i = 0; i < NumRegistos; i++)
{
Cbox_Ano.Items.Add(new { Value = dados.Rows["Ano"], Id = dados.Rows["IdAno"] });
}
Cbox_Ano.Sorted = true;
}
-----------------------------------------------------------------------
I retrieve the date from the combobox if I choose the first year:

private void Cbox_Ano_TextChanged(object sender, EventArgs e)
{
Console.WriteLine(Cbox_Ano.SelectedItem.ToString());
}


The output is: { Value = 2010, Id = 1 }

How can I get an output similar to:
SelectedValue=2010
SelectedId = 1

Thank you in advance for any help you can give me.
 
There's no need for an anonymous type. Once you have a populated DataTable you bind it to the ComboBox like so:
Cbox_Ano.DisplayMember = "Ano";
Cbox_Ano.ValueMember = "IdAno";
Cbox_Ano.DataSource = dados;

The user will then see just the Ano values in the ComboBox. When they make a selection, the Text property of the ComboBox will return the displayed text, i.e. the Ano value as a String, and the SelectedValue property will return the corresponding IdAno value as an Object reference.
 
Back
Top Bottom