I got it working with adding it to a specified list, but I want to go trough all lists in the site collection. I just cant find out whats making this not work.
Code that works for one list:
void btnAdd_Click(object sender, EventArgs e)
{
try
{
using (SPSite site = new SPSite("http://asdf:150/sites/test"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["test8"];
//Needed?
site.AllowUnsafeUpdates = true;
web.AllowUnsafeUpdates = true;
string mainLocation = list.Fields.Add("New Field", SPFieldType.Text, false, false, null);
readOnly(list, mainLocation);
//Add to default view (will be removed after testing)
SPView view = list.DefaultView;
defaultView(view, "New Field");
}
}
}
catch (Exception ex)
{
}
}
I want to add the field to all lists in the site collection, but I dont know what I could be doing wrong, this is what I have so far.
void btnAdd_Click(object sender, EventArgs e)
{
using (SPSite site = new SPSite("http://asdf:150/sites/test"))
{
using (SPWeb web = site.OpenWeb())
{
//Needed?
site.AllowUnsafeUpdates = true;
web.AllowUnsafeUpdates = true;
try
{
SPListCollection lists = web.Lists; // ??
foreach (SPList list in lists)
{
string mainLocation = list.Fields.Add("New Field", SPFieldType.Text, false, false, null);
readOnly(list, mainLocation);
//Add to default view (will be removed after testing)
SPView view = list.DefaultView;
defaultView(view, "New Field");
}
}
catch (Exception)
{
// some exception handling
}
finally
{
//web.Dispose();
}
}
}
}
Helper methods
void readOnly(SPList list, string name)
{
SPField listField = list.Fields.GetFieldByInternalName(name);
listField.ReadOnlyField = true;
listField.Update();
}
void defaultView(SPView view, string field)
{
view.ViewFields.Add(field);
view.Update();
}
Hope any any one of you are smarter then me here 🙂
I run your code and you have 2 main problems.
1. Default view can bu null in some lists. So you should check it.
2. SPListCollection is modified, when you make changes to list. You should have
temporary IEnumerable for iterating through lists.
3. Do not ignore Excaptions. Add some code to catch block, that can help you.