Tapping "Cancel" of a SearchBar is crashing the app in Xamarin.iOS project

Shantimohan Elchuri 721 Reputation points
2021-07-22T17:36:54.877+00:00

I have a search bar in my app. Along with x a clickable button named "Cancel" appears on iOS. No issues clicking the x to clear the text. But when I clicked the "Cancel" button the app is crashing. This "Cancel" buttone doesn't appear in Android. And there is no event name like "CancelClicked" for SearchBar.

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,348 questions
{count} votes

Accepted answer
  1. Shantimohan Elchuri 721 Reputation points
    2021-08-06T18:36:20.487+00:00

    @Wenyan Zhang (Shanghai Wicresoft Co,.Ltd.) I got the solution. Fortunately when I was debugging on a device, tapping the Cancel button broke in SearchBar_TextChanged event pointing to what element is null. It is none other than the SearchBar.Text. So testing for null before using it resolved the issue. The code is as below:

    private void sbSearchData_TextChanged(object sender, TextChangedEventArgs e)  
    {  
        SearchBar sb = (SearchBar)sender;  
    
        // This test is needed to avoid crashing of iOS app on  
        //    tapping the Cancel button that appears when something  
        //    is entered into the SearchBar's text box.  
        if (!string.IsNullOrEmpty(sb.Text))  
        {  
            itemsVM.searchFilter = sb.Text.Trim().ToLower();  
            itemsVM.LoadItemsCommand.Execute(null);  
        }  
    
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.