0
 _site = new SPSite("http:\\MySite");
 _web = site.OpenWeb();

{
   list = _web.Lists[sListName];
   _web.AllowUnsafeUpdates = true;
   items = list.Items;
   item = items.Add();

   item["Title"] = "new Title";
   item["UserName"] = CurrentUser.ToString();
   item["Configuration"] = sConfiguration.ToString();
}

item.Update();
_web.AllowUnsafeUpdates = false;
4

3 回答 3

2
_web = site.OpenWeb();

难道不应该_web = _site.OpenWeb();

于 2010-04-08T07:39:43.417 回答
2

尝试使用 SPQuery 添加项目,例如:

   public static SPListItem OptimizedAddItem(SPList list)
   {
       const string EmptyQuery = "0";
       SPQuery q = new SPQuery { Query = EmptyQuery };
       return list.GetItems(q).Add();
   }
于 2010-11-23T07:47:57.220 回答
1

如果你可以得到 ArgumentNullException

  • 当前用户为空
  • sConfiguration 为空

你必须编写这样的代码:

             using (_site = new SPSite("http:\\MySite")) //Disposing correctly to prevent memory leaks
             using (_web = _site.OpenWeb())
             {
                 try {
                   list = _web.Lists[sListName]; //SPException may be thrown if sListName does not exist
                   _web.AllowUnsafeUpdates = true;
                   items = list.Items;
                   item = items.Add(); //Before doing this, check if you have permissions with list.DoesUserHavePermissions to add items to prevent exception here

                   item["Title"] = "new Title";
                   item["UserName"] = CurrentUser.ToString(); //Not sure which, but some exception may be thrown if such field does not exist and ArgumentNullException may be thrown if CurrentUser is null
                   item["Configuration"] = sConfiguration.ToString(); //ArgumentNullException may be thrown
                   item.Update();
                 }
                 finally {
                   _web.AllowUnsafeUpdates = false;
                 }
             }
于 2010-04-08T06:40:10.523 回答