Search code examples
c#wpfdata-bindingcombobox

Cannot get xml data into comboBox for wpf application


I'm a noob programmer trying to learn more, but stuck on this problem. I've never referenced an external file for data within my UI. I'm unable to update my combobox data to contain the numbers of the projects>project. Not too sure where to go from here.

C# from double clicking the combobox in the MainWindow.xaml editor:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
    {

    }

    private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        XDocument doc = XDocument.Load(@"C: \Users\kaleh\source\repos\Atlas\output.xml");
        var numbers = from n in doc.Root.Elements("project").Elements("number") select n.Value;
        this.comboBox1.ItemsSource = numbers;

    }
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        comboBox1_SelectionChanged(this.comboBox1, null);
    }
}

XML: I'm trying to import just the number of the project into the combobox, I've tried binding in XAML and couldn't get that to work. I'm more familiar with C# so I would like to keep it in C#.

<?xml version="1.0" encoding="UTF-8"?>
<company>
    <projects>
        <project>
            <number>2021-005-00</number>
            <team>
                <member department="mech">Harper, K</member>
                <member department="pm">Logan, C</member>
            </team>
        </project>
        <project>
            <number>2021-004-00</number>
            <team>
                <member department="mech">Gagliardi, G</member>
                <member department="arch">Terranova, N</member>
            </team>
        </project>
    </projects>
</company>

My combobox is still blank and I'm not sure where to go from here.


Solution

  • Two things here.

    One:

    Do not load your combobox in the event selectionchanged. There should be some data to select to trigger selectionchanged. Move it to window constructor or some better place, But after your controls are initialized (after call to InitializeComponent). Example as shown below.

    public MainWindow()
    {
        InitializeComponent();
    
        XDocument doc = XDocument.Load(@"C:\Users\XXXXXXX\Desktop\data\sample.xml");
        var numbers = from n in doc.Descendants("project").Elements("number") select n.Value;
        this.comboBox1.ItemsSource = numbers;
    }
    

    Second:

    Change the LINQ query. Instead of looking in root element, just check for Descendants

    var numbers = from n in doc.Descendants("project").Elements("number") select n.Value;