Click here to Skip to main content
15,881,898 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi All,

I would appreciate if someone could tell me how can i retrieve string value from selected item in a combobox while combobox is binded to object collection (as per code example below).

No matter how i tried only results i get is either empty value or ComboBoxSelectedItem.Person

All i need is a simple example or just explanation what am i doing wrong.

Thank you in advance.

This is my cs code :
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Collections.ObjectModel;

namespace ComboBoxSelectionBinding
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public ObservableCollection<Person> oc;

        public MainWindow()
        {
            InitializeComponent();
            oc = new ObservableCollection<Person>();

            oc.Add(new Person { Username = "Username 1", Name = "name1", Surname = "surname1"});
            oc.Add(new Person { Username = "Username 2", Name = "name2", Surname = "surname2" });
            oc.Add(new Person { Username = "Username 3", Name = "name3", Surname = "surname3" });

            this.DataContext = oc;
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(cbName.SelectedValue.ToString()  + " , "  + oc[0].SelectedUsername);
        }
    }

    public class Person : INotifyPropertyChanged 
    {
        private string username;
        private string name;
        private string surname;
        private string selectedUsername;

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(String propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public string Username
        {
            get { return this.username; }
            set { if (value != this.username) { this.username = value; NotifyPropertyChanged("Username"); } }
        }

        public string Name
        {
            get
            {
                return name;
            }

            set
            {
                if (value != name)
                {
                    name = value;
                    NotifyPropertyChanged("Name");
                }
            }
        }

        public string Surname
        {
            get
            {
                return surname;
            }

            set
            {
                if (value != surname)
                {
                    surname = value;
                    NotifyPropertyChanged("Surname");
                }
            }
        }

        public string SelectedUsername
        {
            get
            {
                return selectedUsername;
            }
            set
            {
                if (value != selectedUsername)
                {
                    this.selectedUsername = value;
                    NotifyPropertyChanged("SelectedUsername");
                }
            }
        }
    }

}


And this my XAML:

XML
<Window x:Class="ComboBoxSelectionBinding.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <ComboBox Name="cbName" ItemsSource="{Binding}" DisplayMemberPath="Username" SelectedValue="{Binding SelectedUsername}"/>
        <Label DataContext="{Binding ElementName=cbName,Path=SelectedItem}" Content="{Binding Name}"/>
        <Label DataContext="{Binding ElementName=cbName, Path=SelectedItem}" Content="{Binding Surname}"/>
        <Button Content="Show Selected Member" Height="23" Name="button1" Width="Auto" Click="button1_Click" />
    </StackPanel>
</Window>
Posted

1 solution

First of all, I would strongly recommend to remove the member SelectedUsername at all. This is an upside-down design and also the violation of the very basic principle "Single Point of Truth". (I cannot refer to "Don't Repeat Yourself"), because you are repeating, but not yourself, but already existing functionality. It also violates natural composition semantics.

Instead, handle selected object outside of the combo box. The property SelectedUsername (instance property!, semantically, has nothing to do with any of the particular instances of the class Person. It really belongs to the combo box, nothing else. Strictly speaking, it could be a property of the class derived from ComboBox, but this would be a great overkill. Much simpler, you can just get the selected object:
C#
Person selectedPerson = (Person)myComboBox.SelectedItem;
// always successful type cast,
// it you populate it only with Person instances

Yes, as simple as that.

There is another (potential?) problem in your code. I would strongly advise you to override System.Object.ToString() in your Person class. What to return? Whatever you want to show on screen in the item, when the instance of this class is added to a list box, combo box, and the like. Could be a Name, Surname, Username, any combination of them in some format, whatever you want. I cannot see where you take care about this string in your XAML, so this easy-to-write overridden function could be handy in this and many other cases.

See also:
http://msdn.microsoft.com/en-us/library/system.windows.controls.combobox%28v=vs.110%29.aspx[^],
http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.selector.selecteditem%28v=vs.110%29.aspx[^],
http://en.wikipedia.org/wiki/Single_Point_of_Truth[^],
http://en.wikipedia.org/wiki/Don%27t_repeat_yourself[^].


—SA
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900