Access SelectedItem from Combobox Windows Forms C #

0

I placed the items inside the combobox as follows:

cmbSituacao.DisplayMember = "Text";
cmbSituacao.ValueMember = "Value";
cmbSituacao.Items.Add(new {Text = "TODOS", Value = "000000"});

foreach(var sit in recSituacao)
{
  cmbSituacao.Items.Add(new {Text = sit.DESCRICAO, Value = sit.ID_SITUACAO });
  cmbSituacao.SelectedIndex = 0;
}

But I can not access the values, follow the code:

object ss = cmbSituacao.SelectedItem;
if (cmbSituacao.GetItemText(cmbSituacao.SelectedItem).Equals("TODOS"))
  filtro = filtro.And(s => s.ID_SITUACAO == cmbSituacao.SelectedValue.ToString());
    
asked by anonymous 19.07.2018 / 16:36

1 answer

0

In fact your code needs several improvements. First, you must use the DataSource property of the ComboBox component to fill the items so that you can use the component's resources correctly. To do this, create a class ViewModel for ComboBox :

public class ComboViewModel
{
    public string Text { get; set; }
    public string Value { get; set; }
}

This class will be your template so create a temporary list that will receive your items and then seven this list as the DataSource property of the component.

List<ComboViewModel> listaTemporaria = new List<ComboViewModel>()
{
    new ComboViewModel { Text = "TODOS", Value = "000000" }
};

listaTemporaria.AddRange(recSituacao.Select(sit => new ComboViewModel{  Text = sit.DESCRICAO, Value = sit.ID_SITUACAO }).ToList());

cmbSituacao.DataSource = listaTemporaria;
cmbSituacao.DisplayMember = "Text";
cmbSituacao.ValueMember = "Value";
cmbSituacao.SelectedIndex = 0;

In front of this when accessing the value selected in the ComboBox use the code below:

ComboViewModel itemSelecionado = cmbSituacao.SelectedItem as ComboViewModel;

if (itemSelecionado != null && itemSelecionado.Text != "TODOS")
  filtro = filtro.And(s => s.ID_SITUACAO == itemSelecionado.Value);

Any questions let me know, I'm out of Visual Studio now and I did it in Notepad, there may be some error.

    
19.07.2018 / 17:13