Creating Lists and updating the default view programatically in SharePoint 2007
Recently a question came across a distribution list that I am a member of about updating the default view through code in SharePoint 2007. Whenever I answer a question like this I try to remember it and blog about it. Hopefully the next time someone is looking for the answer they will search and find this blog entry! So here is a small code sample that creates a list and updates the "All Items" view through code.
private const string MultiLanguageHelloListName = "Multi-Language Hello";
SPSite currentSite = properties.Feature.Parent as SPSite;
SPWeb currentWeb = currentSite.RootWeb;
uint language = currentWeb != null ? currentWeb.Language = 1033;
SPList list = null;
if (!ListExists(currentSite.RootWeb, MultiLanguageHelloListName))
{
Guid listId = currentSite.RootWeb.Lists.Add(MultiLanguageHelloListName,
SPUtility.GetLocalizedString("$Resources:hello,HelloSettingsDesc;", "hello", language),
SPListTemplateType.GenericList);
list = currentSite.RootWeb.Lists[listId];
list.Fields.Add("ToolTip", SPFieldType.Text, true);
SPField tooltip = list.Fields["ToolTip"];
tooltip.ShowInDisplayForm = true;
tooltip.ShowInEditForm = true;
tooltip.ShowInListSettings = true;
tooltip.ShowInNewForm = true;
tooltip.ShowInViewForms = true;
SPView defaultView = list.Views["All Items"];
defaultView.ViewFields.Add(tooltip);
defaultView.Update();
list.ContentTypesEnabled = false;
list.OnQuickLaunch = true;
list.EnableAttachments = false;
list.EnableVersioning = false;
list.NoCrawl = true;
list.Update();
}
The first section of this piece of code verifies that the list doesn't exist, because this piece of code was from a feature receiver in the FeatureActivated event. Next I create the list using currentSite.RootWeb.Lists.Add(<listname>, <list description>, SPListTemplateType). After the creation of the list I go on to add a field called "ToolTip" to the list. I then want to show this field in the deafult view so I get a reference to the "All Items" view and add it to the ViewFields collection. Then update the view and update the list and your done!
Hope this is useful.