Search code examples
c#xmlautocompletewindows-phoneautocompletebox

Autocomplete box error


I have a xml file and I want to search in it with an autocomplete box. I use code below but the it crashed. How can I fix it or is there a way better?

               XDocument loadedData = XDocument.Load("BankCode.xml");

        var data = from query in loadedData.Descendants("BankCode")
                   select new BankData
                   {
                       BankName= (string)query.Element("Bank"),
                   };
        this.acBox.ItemsSource = data;

        XDocument loadedCustomData = XDocument.Load("BankCode.xml");
        var filteredData = from c in loadedCustomData.Descendants("Bank")
                           where c.Attribute("Code").Value == acBox.Text
                           select new BankData()
                           {
                               Code= c.Attribute("Code").Value
                           };
        listBox1.ItemsSource = filteredData;

I want to create an app that when the user type the bank name in autocomplete box after pressing the search button the bank code has shown to him/her. (!!The acBox is an autocomplete box.)


Solution

  • It seems 1 of your Bank nodes does not have a Code attribute. You should add a NULL check:

    var filteredData = from c in loadedCustomData.Descendants("Bank")
                       where c.Attribute("Code") != null && c.Attribute("Code").Value == acBox.Text
                       select new BankData()
                       {
                           Code= c.Attribute("Code").Value
                       };