2013-11-20 69 views
1

我已經能夠以編程方式添加外部(即BDC)查找字段列表,並且我也一直能夠添加依賴外部查找字段添加到同一個列表中。我無法弄清楚的是如何以編程方式將依賴外部查找字段添加到列表的默認視圖。編程到SPView添加依賴外部對照場在SharePoint 2010

This文章在MSDN上提供如何定期依賴查找字段添加到SPView一個例子 - 但是我還沒有找到,說明如何依賴外部查找字段以編程方式添加到SPView爲例。

下面是我使用的EventReceiver的FeatureActivated方法中的代碼,用於將依賴的外部查找字段添加到我的SharePoint列表中,並嘗試將該字段添加到列表的默認視圖。

var web = ((SPSite)properties.Feature.Parent).RootWeb; 
var list = web.Lists.TryGetList("MyList"); 
var fldName = "EmployeeID"; 

var fld = list.Fields.CreateNewField("BusinessData", fldName) as SPBusinessDataField; 

fld.SystemInstanceName = lobSystemInstanceName; 
fld.EntityNamespace = entityNamespace; 
fld.EntityName = entityName; 
fld.BdcFieldName = entityFieldName; 

//The dictionary object defined below contains key/value pairs that represent the 
//field name as a string along with a boolean flag that specifies whether or not 
//the secondary field should be added to the default view. 
var secondaryFieldNames = new Dictionary<string, bool>() 
         { 
          {"FirstName", true}, 
          {"LastName", true}, 
          {"Title", false} 
         } 
fld.SetSecondaryFieldsNames(secondaryFieldNames.Select(e => e.Key).ToArray()); 

var view = list.Views.DefaultView; 

foreach (var secFld in secondaryFieldNames) 
{ 
    var viewFieldName = String.Format("{0}: {1}", fldName, secFld.Key); 

    if (!view.ViewFields.Exists(viewFieldName) && secFld.Value) 
    { 
      view.ViewFields.Add(viewFieldName); 
      view.Update(); 
    } 
} 

如前所述,主查找字段和所有輔助查找字段已成功添加到列表中。主查找字段已成功添加到列表的默認視圖。次要領域不是。

回答

0

將viewfield集合存儲在一個變量中對我來說是個詭計(不知道爲什麼)。

foreach (var secFld in secondaryFieldNames) 
      { 
       var viewFieldName = String.Format("{0}: {1}", fldName, secFld.Key); 
       var viewFields = view.ViewFields; 
       if (!viewFields.Exists(viewFieldName) && secFld.Value) 
       { 
        viewFields.Add(viewFieldName); 
        view.Update(); 
       } 
      }