Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

Cannot implicitly convert type 'bool? ' To 'bool'. An explicit conversion exists (are you missing a cast? ) with listbox selected In MVC?

C#
public ActionResult Index()
        {
            SampleDBContext db = new SampleDBContext();
            List<SelectListItem> listSelectListItem = new List<SelectListItem>();
            foreach (City city in db.Cities)
            {
                SelectListItem selectListItem = new SelectListItem()
                {
                    Text=city.Name,
                    Value=city.ID.ToString(),
                    Selected=city.IsSelected //Error
                };
                listSelectListItem.Add(selectListItem);
            }
            return View();
        }


Every time its getting error with boolean variable IsSelected.
how can we resolve this error?
Please help me.

Thanks in Advance.

Ankit Agarwal
Software Engineer

What I have tried:

C#
public ActionResult Index()
        {
            SampleDBContext db = new SampleDBContext();
            List<SelectListItem> listSelectListItem = new List<SelectListItem>();
            foreach (City city in db.Cities)
            {
                SelectListItem selectListItem = new SelectListItem()
                {
                    Text=city.Name,
                    Value=city.ID.ToString(),
                    Selected=city.IsSelected // Error
                };
                listSelectListItem.Add(selectListItem);
            }
            return View();
        }
Posted
Updated 15-Dec-16 23:55pm

Type cast it like Selected=(bool)city.IsSelected if Selected property is boolan
 
Share this answer
 
Comments
Agarwal1984 16-Dec-16 1:54am    
Thanks
Hi,

Note here, SelectListItem Selected property datatype is bool.

Please check your city.IsSelected datatype. I am sure it is bool? .

If city.IsSelected is nullable bool type (bool?) then you cannot assign as it is to bool variable. so you need to assign its value like below

Selected= city.IsSelected.HasValue ? city.IsSelected.Value : false;
 
Share this answer
 
v2
Casting is expensive. Do it this way.

C#
Selected = (city.IsSelected == true)
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900