0

Sorry for posting kind of a repeated question. Due to my reputation, i couldn't post a question in the comments of Hidden Id With ComboBox Items?

How can i select an item from the ComboBox depending upon the HiddenID?

SQL Example : "Select displayValue from ComboList where hiddenValue = 10"

For the convenience, I'm pasting the code from the above link.

public class ComboBoxItem()
{
   string displayValue;
   string hiddenValue;

   //Constructor
   public ComboBoxItem (string d, string h)
   {
        displayValue = d;
        hiddenValue = h;
   }

   //Accessor
   public string HiddenValue
   {
        get
        {
             return hiddenValue;
        }
   }

   //Override ToString method
   public override string ToString()
   {
        return displayValue;
   }
}

And then in your code:

//Add item to ComboBox:
ComboBox.Items.Add(new ComboBoxItem("DisplayValue", "HiddenValue");

//Get hidden value of selected item:
string hValue = ((ComboBoxItem)ComboBox.SelectedItem).HiddenValue;
Community
  • 1
  • 1
Shallo
  • 43
  • 13

1 Answers1

1

You are adding directly to the combobox control the items. What I have done is created a List<> of the combobox item custom class you had. Then set the combobox item source to the list (virtually the same), but by doing this, I can explicitly tell the combobox what property of the control is the SELECTED value vs the DISPLAY value (cant set both). So, I have the following..

List<ComboBoxItem> myList = new List<ComboBoxItem>();
myList.Add(new ComboBoxItem("Display Only", "I am Hidden"));
myList.Add(new ComboBoxItem("2nd line", "HV2"));
myList.Add(new ComboBoxItem("Show 3", "S3"));

ComboBox myCombo = new ComboBox();
myCombo.ItemsSource = myList;
myCombo.SelectedValuePath = "HiddenValue";

// specifically tell the combobox which "Hidden" value you want to set it to
myCombo.SelectedValue = "HV2";
//Get hidden value of selected item: should show "2nd line"
string showValue = myCombo.Text;
MessageBox.Show(showValue);
DRapp
  • 47,638
  • 12
  • 72
  • 142
  • While it works, I would highly suggest doing this in the XAML instead of code behind like this. Still +1. – Kelly Feb 25 '16 at 06:36
  • @Kelly, I understand, but what if the list is being prepared dynamically from some data source. Yes, the bindings could be tied to the view model, but at least this exposes where the pieces are for the user otherwise. – DRapp Feb 25 '16 at 11:18