Search code examples
c#wpfcombobox

C# WPF Combobox selection event based on Combobox list populated from text file


I have a Combobox drop down that is populated from a text file. The combobox is populated with multiple server groups. This is working fine.

servergroups.txt
Group1
Group2
Group3
       public MainWindow()
        {
            InitializeComponent();
            ComboBox2.ItemsSource = File.ReadAllLines(@"c:\temp\servergroups.txt");
        }

The problem i have is that i am also trying to populate a listbox of servers from a server text file based on what server group selected in the combobox.

group1.txt
server1
server2
server3
        private void ComboBox2_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (((ComboBoxItem)ComboBox2.SelectedItem).Content.Equals("Group1"))
            {
                Listbox1.ItemsSource = null;
                Listbox1.Items.Clear();
                Listbox1.ItemsSource = File.ReadAllLines(@"c:\temp\Group1.txt");
                Listbox1.ScrollIntoView(Listbox1.Items[0]);
            }

I am getting the following exception when i select any item from the combobox dropdown

System.InvalidCastException: 'Unable to cast object of type 'System.String' to type 'System.Windows.Controls.ComboBoxItem'.'

thank you!


Solution

  • The error message clearly says that SelectedItem is of type string.

    When you assign a collection of strings to the ItemsSource property of a Selector, the SelectedItem is also a string:

    if ((string)ComboBox2.SelectedItem == "Group1")
    {
        Listbox1.ItemsSource = File.ReadAllLines(@"c:\temp\Group1.txt");
    }
    

    In general, the object held by the SelectedItem property is the currently selected element in the Items collection, so that the following condition is true when SelectedIndex >= 0:

    selector.SelectedItem == selector.Items[selector.SelectedIndex]