Access Combobox Selecteditem Windows Forms C#

Asked

Viewed 447 times

0

I put 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’t 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());
  • You can’t, why?

  • because when I access the Selectedit it does not provide the "Text" nor the "Value", there in the image it is returning the Text because I am using the Getitemtext, but I really need to access the "Value" and this I can not for anything, any idea?

  • as the name says, it’s a SelectedItem, that is, the same object that you created, and from it you can access Text and Value

  • Trade the image for your code

  • Thank you, the concept I know, I want to understand how to access, you would know, using my code above? Ricardo Punctual

1 answer

0


Actually your code needs several improvements. First you should use the property DataSource of the component ComboBox to fill in the items so that you can use the component’s resources correctly. To do this, create a class ViewModel to the 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 property DataSource 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;

Before this when accessing the selected value in 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 am without Visual Studio now and I did in the notebook, there may be some mistake.

  • Julio Borges, that’s exactly what it was, thanks for your help!

  • @user2929918 OK, accept the answer please, to help other people who have the same question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.