Inconvenient StringToSPViewType (Programmatically adding Views)


I’ve just stumbled upon a little inconvenience within SharePoint object model. As I needed to programmatically add a new View to a list, I have used the StringToSPViewType method of SPViewCollection class to convert a string representation of the view type to its SPViewType equivalent. Unfortunately all what I’ve got was an Argument Exception: Value does not fall within the expected range. Using the Lutz Roeder’s Reflector I’ve taken a look into the assembly and I’ve found the reason of this problem.

If you look at the SDK SPViewType enumeration definition, you will see that all the values are given using Pascal case, eg. Html. But if you pass your string equivalent (“Html”) it won’t work and furthermore it will result in a exception. It has to do with the way SharePoint object model converts the string value to SPViewType. It uses a dictionary with the same values as given by the SDK but then written uppercase! If you try to get a value of the Html dictionary item it fails, because there is HTML only within the dictionary.

I think the way this method should be used in scripting scenario’s is to use the SDK values and make this uppercase within the custom method before passing it to the StringToSPViewType method.

Others found also helpful: