Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get selected item's Tag in ComboBox?

I have an ComboBox that contains some items that have a Tag, which I need to associated them to the database (Tag contains Id in database), but I don’t know how to get the it.
I tried this but it doesn’t work. It says you can’t convert string to ComboBox.

var cbi = (ComboBoxItem)PropertyTemplateList.SelectedItem;

var Id = Convert.ToInt64(cbi.Tag);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can ask the ItemContainerGenerator of the ComboBox for the item container, a ComboBoxItem.

var item = PropertyTemplateList.SelectedItem;
var cbi = (ComboBoxItem)PropertyTemplateList.ItemContainerGenerator.ContainerFromItem(item);

if (cbi is null)
{
   // ...handle nothing selected.
   return;
}
else
{
   var Id = Convert.ToInt64(cbi.Tag);

   // ...do something.
   return;
}

This works both for binding an ItemsSource and hardcoded ComboBoxItems.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading