ComboBox is not being populated by the Items I want

6

I have a ComboBox filled in from a list created with information obtained from a txt file. But instead of being filled with the information of the file he is receiving inside it ----- > GeraRelatorio.Planta , would you like to know why?

private void Form1_Load(object sender, EventArgs e)
{
    dateInicial.Value = DateTime.Today.AddDays(-1);
    dateFinal.Value = DateTime.Today.AddDays(-1);
    textBox1.MaxLength = 20;

    comboBanco.Items.Clear();
    List<Planta> plantas = new List<Planta>();

    using (StreamReader arquivo = File.OpenText(@"C:\Conexoes\Estados.txt"))
    {
        string linha;
        while ((linha = arquivo.ReadLine()) != null)
        {
            var espaçoArquivo = linha.Split(';');

            var planta = new Planta();
            planta.Local = espaçoArquivo[0];
            planta.Conexao = espaçoArquivo[1];

            plantas.Add(planta);
        }

    }

    foreach (Planta result in plantas)
    {
        comboBanco.Items.Add(result);
    }


}

private void comboBanco_SelectedIndexChanged(object sender, EventArgs e)
{
    comboBanco.SendToBack();
    FrmGrid formb = new FrmGrid();

    switch (((Planta)comboBanco.SelectedItem).Local)
    {
        case "CT":
            formb.lblLocal.Text = ((Planta)comboBanco.SelectedItem).Local;
            formb.lblConexao.Text = ((Planta)comboBanco.SelectedItem).Conexao;
            formb.Show();
            break;

        case "CU":
            formb.lblLocal.Text = ((Planta)comboBanco.SelectedItem).Local;
            formb.lblConexao.Text = ((Planta)comboBanco.SelectedItem).Conexao;
            formb.Show();
            break;

        case "AT":
            formb.lblLocal.Text = ((Planta)comboBanco.SelectedItem).Local;
            formb.lblConexao.Text = ((Planta)comboBanco.SelectedItem).Conexao;
            formb.Show();
            break;

        default:
            break;
    }
}

class Planta
{
    public string Local { get; set; }
    public string Conexao { get; set; }
}
    
asked by anonymous 27.08.2018 / 14:14

2 answers

8

As you are filling your combobox with a list of an entity, we need to tell you what field in that class represents the description that will be demonstrated and the value that that description represents.

Define a value (remembering that some property of your class Planta must be) for the DisplayMember property of your combobox to display the text for the user:

comboBanco.DisplayMember = "Local";

Set a value (remembering that some property of your Planta class must be) for the ValueMember property of your combobox to set the value for the selected item:

comboBanco.ValueMember = "Conexao";
    
27.08.2018 / 14:30
2

Instead of adding Planta to your ComboBox , add SelectListItem .

foreach (Planta result in plantas)
{
    var item = new SelectListItem() { Text = result.Local, Value = result.Conexao }
    comboBanco.Items.Add(item);
}
    
27.08.2018 / 14:33