locked
How to avoid Object Reference to null? RRS feed

  • Question

  • Hi,

    I am using this if condition to search the data:

    if (services.first_name.ToLower().Contains(searchBar.Text.ToLower()) || services.middle_name.ToLower().Contains(searchBar.Text.ToLower()) || services.last_name.ToLower().Contains(searchBar.Text.ToLower()) || services.email_address.ToString().Contains(searchBar.Text.ToLower()))

    My data is like this:

    public class UsersData
    {
        public int user_id { get; set; }
        public string first_name { get; set; }
        public string middle_name { get; set; }
        public string last_name { get; set; }
        public string email_address { get; set; }
    
        public string full_name
        {
            get
            {
                string user_full_name;
    
                user_full_name = first_name;
                user_full_name += " " + middle_name;
                user_full_name += " " + last_name;
    
                return user_full_name;
            }
        }
    
        public string user_image
        {
            get
            {
                return string.Format("https://www.ajworld.app/gallery/photos/{0}.png", user_id);
            }
        }
    }
    


    but some values might be null in MySQL which cause a crash in my code, e.g. middle_name

    How can i solve this please?

    Thanks,

    Jassim

    Tuesday, June 30, 2020 7:15 AM

Answers

  • Try this kind of conditions:

    if( services.first_name?.ToLower()?.Contains(searchBar.Text.ToLower()) == true || etc…

    or:

    if( services.first_name?.Contains(searchBar.Text, StringComparison.CurrentCultureIgnoreCase) == true || etc…


    • Edited by Viorel_MVP Tuesday, June 30, 2020 7:39 AM
    • Marked as answer by Jassim Rahma Tuesday, June 30, 2020 8:41 AM
    Tuesday, June 30, 2020 7:37 AM