I think I grew a grey hair on this one today. It is so simple and yet I could not figure out why on earth it was so anoying to read this bool from a listitem ![]()
Let me sum up what I wanted:
I have a webpart that shows document library files and folders in a treeview.
In each document library there is a column with a Yes / No (checkbox) called “Show File”.
The webpart was modified with a checkbox that indicates if all files should be shown or only the ones that are checked in the “Show File” field.
In the webpart I iterate through all webs and all lists and then check if any of the lists have the “Show File” column, if they do I will add them to the TreeView and then iterate through the files and folders of that particular document library.
When iterating through the files I had to read the value of the field, which proved to be different than what I expected.
Basically I had a File object and wanted to check the field value. I tried some of the following, and had a list reference and file reference at hand (solution at the bottom):
SPListItem listItem = list.GetItemByUniqueId(file.UniqueId); if(listItem["Show Document"].ToString().ToLower() == "true") //And display name "Show Document too){//Do something}
if(file.Item.Fields["Show Document"].ToString().ToLower() == "true") // ("Show Document" too){//Do something}
Messed around with:
SPFieldBoolean showDocument = file.Item.Fields["Show Document"];
if((bool)file.Item["Show Document"] == true){//Do something}
if(file.Item.Fields["Show Document"].ToString().ToLower() == "1"){//Do something}
if(file.Item.Fields["Show Document"] == true){//Do something}
if(file.Item.Fields["Show Document"] == "true"){//Do something}
if(file.Item.Fields["Show Document"] == true){//Do something}
if (Convert.ToBoolean(file.Item["Show Document"]) == true){//Do something}
The above is what worked for me.
I wondered why on earth it should be so hard for someone like me to read such a simple value…. *sigh*, but then again maybe it’s just me that had this problem, and I’m just being silly.
If any of you have some other solutions to reading this type of value please leave info about it, I am sure it will help more than just me.
I found the help to do this on a post by Isha Kapoor which was about SPQuery with Yes / No columns, but unfortunately it took me a while t admit I was stuck and then finding this hint that helped me took a while :-]
Related posts:
if (Convert.ToBoolean(itemCollection[0]["IsToDo?"].ToString()) == true)
{
// go something
}
this work for me !!!
Thanks, this helped me!
A quick addition though, you don’t need the “== true” part in an IF statement. You could just cut it down to this:
if (Convert.ToBoolean(file.Item["Show Document"]))
{
//Do something
}
You are perfectly right. Thanks for pointing out the slightly bloated code