2013-09-30 26 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:你读过'你也可以改变'部分吗? –

相关问题