2013-09-30 28 views
0

我正在使用List對象來存儲用戶屬性。指數超出範圍。必須是非負的並且小於列表中的集合的大小<string>

我的代碼是:

string department=string.Empty; 
List<string> otherDepartments = new List<string>(); 
int no; 
string result = string.Empty; 

string queryText = string.Empty; 
using (SPSite siteCollection = SPContext.Current.Site) 
{ 
    using(SPWeb site = siteCollection.OpenWeb()) 
    { 
     SPSecurity.RunWithElevatedPrivileges(delegate() 
     { 
       SPUser spUser = site.CurrentUser;       
       SPServiceContext context = SPServiceContext.GetContext(siteCollection); 
       UserProfileManager upm = new UserProfileManager(context); 
       UserProfile profile = upm.GetUserProfile(spUser.LoginName); 
       department = profile["oiplbDepartment"].Value.ToString(); 

       UserProfileValueCollection otherDept = profile["oiplbOtherDepartments"]; 

       if (otherDept.Count != 0) 
       {       
        foreach (var prop in otherDept) 
        { 
         otherDepartments.Add(prop.ToString()); 
        } 
       } 
       Label1.Text = department + " Ohter Departments " + otherDepartments; 
      }); 

      SPList list = site.Lists["Events"]; 
      SPListItemCollection itemColl; 
      SPQuery query = new SPQuery(); 
      no = 1 + otherDepartments.Count; 
      for (int i = 1; i <= no; i++) 
      { 
       if (no == 1) 
       { 
        result = "<or> <Eq><FieldRef Name='oiplbDepartment' /><Value Type='TaxonomyFieldType'>"+department+"</Value></Eq>"+"</or>"; 
        break; 
       } 
       else if (i == 2) 
       { 
        result = "<or> <Eq><FieldRef Name='oiplbDepartment' /><Value Type='TaxonomyFieldType'>" + department + "</Value></Eq>" + 
        "<Eq><FieldRef Name='oiplbDepartment' /><Value Type='TaxonomyFieldType'>" + otherDepartments[i-1] + "</Value></Eq>"; 
       } 
       else if(i >= 3) 
       { 
        result = generateOr(result,otherDepartments[i-1]); 
       } 
     }         
     queryText = "<where>"+result +"</Where>"; 
     query.Query = queryText; 
     itemColl = list.GetItems(query); 
     Grid.DataSource = itemColl.GetDataTable(); 
     Grid.DataBind(); 
    } 
} 

public static string generateOr(string temp, string value) 
{ 
    string r = "<or>" + temp + " <Eq><FieldRef Name='oiplbDepartment' /><Value Type='TaxonomyFieldType'>" + value + "</Value></Eq> </or>"; 
    return r; 
} 

當我運行程序我得到上述錯誤。

我插入一個值當且僅當屬性可用否則不可用。

但是,爲什麼我會收到錯誤?

+0

那麼在哪一行? – Arran

+0

嘗試改變這一行:'for(int i = 1; i <= no; i ++)'to(for i = 1; i

+0

必須包含至少1的值,所以如果我在for循環中改變類似'for(int i = 1,k = 0; i <= no; i ++,k ++ 0')並通過'k'訪問列表索引將起作用嗎? –

回答

4

其因

no = 1 + otherDepartments.Count; 

改變它

no = otherDepartments.Count; 

即使你從i減去1,你在列表中訪問項目的for-loop循環,直到i == no之前。所以你也可以將i <= no更改爲i < no

for (int i = 1; i < no; i++) 
+0

謝謝先生,問題是數量必須至少爲1,所以我該怎麼辦?這是因爲用戶至少屬於一個部門。 –

+0

@RiyazKalva:你讀過'你也可以改變'部分嗎? –

相關問題