Code compiles properly but while running gives error

  private ObservableCollection<Contact> GetContacts(String SearchText = null)
        {
            _contacts = new ObservableCollection<Contact>
            {
                new Contact{Name = "mosh",Status ="hi",ImageUrl= "http://lorempixel.com/100/100/people/1"  },
                 new Contact{Name = "josh",Status ="halo",ImageUrl= "http://lorempixel.com/100/100/people/2"  }
            };
            if (String.IsNullOrWhiteSpace(SearchText))
                return _contacts;
            else
              return (ObservableCollection<Contact>)_contacts.Where(c => c.Name.StartsWith(SearchText));[/b]
        }
      

Open in new window



while  implementing search  functionality in contacts I  am  getting error  at  lastline.Code  compiles perfectly while  running  gives error.
If  I  make  return  type  IEnumerable  problem  might get solved  but  delete  contact  functionality  might  not refresh  list.
I  have  attached  xaml and  cs  file  to this  question  ,please  help
ContextListPage.xaml
ContextListPage.xaml.cs
ADITYA RAOSoftware DeveloperAsked:
Who is Participating?
 
Fernando SotoConnect With a Mentor RetiredCommented:
Hi ADITYA RAO;

As the exception stated you have an invalid cast being thrown. This will happen when the SearchText is not null and the else part of the if statement is taken this is because the query is returning a IEnumerable<Contact> and NOT an ObservableCollection and can not be directly cast to one. Change your if statement as follows.
if (String.IsNullOrWhiteSpace(SearchText))
    return _contacts;
else
    return new ObservableCollection<Contact>(_contacts.Where(c => c.Name.StartsWith(SearchText)));

Open in new window

0
 
ste5anSenior DeveloperCommented:
What exact error do you get?
0
 
ADITYA RAOSoftware DeveloperAuthor Commented:
Unhandled Exception:

System.InvalidCastException: Specified cast is not valid. occurred
0
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
ADITYA RAOSoftware DeveloperAuthor Commented:
0
 
Fernando SotoConnect With a Mentor RetiredCommented:
Please post the code where you defined the variable _contacts.
0
 
ADITYA RAOSoftware DeveloperAuthor Commented:
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using ContextList.Model;
using System.Collections.ObjectModel;

namespace ContextList
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class ContextListPage : ContentPage
    {
        private ObservableCollection<Contact> _contacts;
        public ContextListPage()
        {
            InitializeComponent();

            myContextList.ItemsSource = GetContacts();
        }

        private void CallClicked(object sender, EventArgs e)
        {
            var menuitem = sender as MenuItem;
            var con = menuitem.CommandParameter as Contact;
            DisplayAlert("Call Clicked", con.Name, "OK");
        }

        private void DeleteClicked(object sender, EventArgs e)
        {
            var menuitem = sender as MenuItem;
            var con = menuitem.CommandParameter as Contact;
            _contacts.Remove(con);
        }

        private void myContextList_Refreshing(object sender, EventArgs e)
        {
            myContextList.ItemsSource = GetContacts();
            myContextList.EndRefresh();
        }

        private ObservableCollection<Contact> GetContacts(String SearchText = null)
        {
            _contacts = new ObservableCollection<Contact>
            {
                new Contact{Name = "mosh",Status ="hi",ImageUrl= "http://lorempixel.com/100/100/people/1"  },
                 new Contact{Name = "josh",Status ="halo",ImageUrl= "http://lorempixel.com/100/100/people/2"  }
            };
            if (String.IsNullOrWhiteSpace(SearchText))
                return _contacts;
            else
                return (ObservableCollection<Contact>)_contacts.Where(c => c.Name.StartsWith(SearchText));
        }

        private void SearchBar_TextChanged(object sender, TextChangedEventArgs e)
        {
            GetContacts(e.NewTextValue);
        }
    }
}

Open in new window

0
 
ADITYA RAOSoftware DeveloperAuthor Commented:
It  is same file ContextListPage.xaml.cs,please see  see  top 8th line
0
 
ADITYA RAOSoftware DeveloperAuthor Commented:
Thank you very much It  resolved  my  issue
0
 
Fernando SotoRetiredCommented:
Not a problem Aditya, glad to help.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.