Combobox.SelectedIndex does not return the item in Windows Forms

0

I have a program in windows forms and I need to select the item in a combo box so that the user can edit the registry, however, it receives the value, finds the index but does not return the selected screen. follow the code:

private void PreencherCbox(List<Natureza> lista)
    {
        List<CboxModel> model = new List<CboxModel>();

        CboxModel p = new CboxModel();

        p.Text = "Selecione uma natureza";
        p.Value = "0";

        model.Add(p);

        foreach (Natureza n in lista)
        {
            CboxModel m = new CboxModel();
            m.Text = n.Descricao;
            m.Value = n.Id.ToString();

            model.Add(m);
        }

        this.CboxNatureza.DataSource = model;
        CboxNatureza.DisplayMember = "Text";
        CboxNatureza.ValueMember = "Value";
    }

and at the time of receiving the value and selecting:

this.CboxNatureza.SelectedIndex = CboxNatureza.FindStringExact(e.Natureza.Descricao);

I have another code snippet that is the same, but it works. Help! = D

    
asked by anonymous 27.04.2018 / 22:05

1 answer

0

You are creating a template ( CboxModel ), just to add a simple text (Select a nature), have you tried using Label to illustrate this text?

Try this:

  
  • Theproperty.SelectedIndexgets-1,leavesthetextfieldempty.
  •   
  • Usethe.SelectedValuepropertytoreturntheitem,butnotethatthe.ValueMemberpropertywasfedwiththe'ID'field  ofclassNaturezawhichisinList<>,soitisgoingto  returnsanumber.
  •   
  • Thereturntypeof.SelectedValueisaobject,sodependingontheusage,watchoutforthetreatment.
  •   

Soonyourcodewouldlooklikethis:

//-->SeuMétodoprivatevoidPreencherCbox(List<Natureza>lista){this.CboxNatureza.DataSource=lista;CboxNatureza.DisplayMember="Descricao";
   CboxNatureza.ValueMember = "Id";
   CboxNatureza.SelectedIndex = -1;       
}
    
28.04.2018 / 05:28