0

I am working on a ListView n Xamarin.Forms which includes Tools. The user should be able to search for the kind of tool and tool location. My code works just fine if you first type in both search criteria. After that you can perform a new search leaving out e.g the tool location, also working fine. But if you start by just typing in one criteria, the application stops. Doesn't make any sense to me as it seems to work after putting in both criteria. Can anyone tell me what i'm missing here?

private void Btn_Search_Clicked(object sender, EventArgs e)     
   {   
            var container = BindingContext as ToolViewModel;
            var searchValueToolDescription = SfEntry_ToolType.Text;
            var searchValueToolLocation = SfEntry_ToolLocation.Text;
            var searchValueToolPrice = SfEntry_ToolPrice.Text;

            listTools.BeginRefresh();

            listTools.ItemsSource = container.Tools.Where(i => 
            i.ToolDescription.Contains(searchValueToolDescription) && 
            i.ToolLocation.Contains(searchValueToolLocation));

        }
DeSchm
  • 1
  • 1
  • Split your 'Where' clause in two, so you could check if the first or second criteria is null, then apply the where statement. Perhaps it helps: https://stackoverflow.com/questions/977159/linq-to-sql-and-null-strings-how-do-i-use-contains – Bruno Apr 19 '19 at 09:00

1 Answers1

0

try breaking the query up into three cases. There are probably clever ways you could do this with single query, but they would be less readable

// desc and loc
if (!string.IsNullOrEmpty(searchValueToolDescription) && !string.IsNullOrEmpty(searchValueToolLocation)) {
    listTools.ItemsSource = container.Tools.Where(i => 
        i.ToolDescription.Contains(searchValueToolDescription) && 
        i.ToolLocation.Contains(searchValueToolLocation));
} 
// just desc
else if (!string.IsNullOrEmpty(searchValueToolDescription)) {
    listTools.ItemsSource = container.Tools.Where(i => 
        i.ToolDescription.Contains(searchValueToolDescription)); 
} 
// just loc
else if (!string.IsNullOrEmpty(searchValueToolLocation)) {
    listTools.ItemsSource = container.Tools.Where(i => 
        i.ToolLocation.Contains(searchValueToolLocation));
}
Jason
  • 86,222
  • 15
  • 131
  • 146