bsquared
bsquared

Reputation: 137

Converting an int to string for a searchbar function C#

I have written an application in ASP.NET MVC and have implemented a search bar. This search bar is enabled for multiple fields. The problem I am having is enabling the search for an ID field of type int. It seems like I need to only have string values in my search field. Is there a way to convert the ID field to string type so I can also be able to search for that?

Here is the code i'm using. It works for first name and last name, but not when I have the ID part enabled.

Any help is appreciated!

 public ActionResult Index(string sortOrder, string currentFilter, string searchString, int? page)
    {
        ViewBag.LastSortParm = sortOrder == "LastName" ? "LastDesc" : "LastName";

        ViewBag.FirstSortParm = sortOrder == "FirstName" ? "FirstDesc" : "FirstName";

        ViewBag.IDSortParm = sortOrder == "ID" ? "RVHDesc" : "ID";

  if (!String.IsNullOrEmpty(searchString)) //creates the code for the search bar
        {
            doctors = doctors.Where(d => d.Last_Name.ToUpper().Contains(searchString.ToUpper()) //insert to upper or lower so that case is ignored
                                   || d.First_Name.ToUpper().Contains(searchString.ToUpper()));
             || d.RVH_ID_.ToUpper().Contains(searchString.ToUpper()));
        }
}

Upvotes: 0

Views: 1431

Answers (1)

dub stylee
dub stylee

Reputation: 3342

If your d.RVH_ID_ field is an int then you will need to call ToString() on it before your ToUpper() call. Try this:

doctors = doctors.Where(d => d.Last_Name.ToUpper().Contains(searchString.ToUpper())
         || d.First_Name.ToUpper().Contains(searchString.ToUpper())
         || d.RVH_ID_.ToString().ToUpper().Contains(searchString.ToUpper()));

As @wgraham mentions in his comment above, since an int has no uppercase/lowercase, the ToUpper() call is not necessary. However, there is no ToString() overload for int in Linq, so you have to cast it to double or decimal according to this answer.

Example: SqlFunctions.StringConvert((double)d.RVH_ID_).Contains(searchString)

Upvotes: 1

Related Questions