我可以将其添加到指定列表中,但我想浏览网站集中的所有列表。我只是不知道是什么让这不起作用。
适用于一个列表的代码:
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)
{
}
}
我想将该字段添加到网站集中的所有列表中,但我不知道我可能做错了什么,这就是我到目前为止所拥有的。
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();
}
}
}
}
辅助方法
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();
}
希望你们中的任何一个人都比我聪明:)