开发者

I am adding a new splistitem to a sharepoint list but it always gives me an exception: "object reference not set to an instance of an object"

开发者 https://www.devze.com 2022-12-26 06:15 出处:网络
_site = new SPSite(\"http:\\\\MySite\"); _web = site.OpenWeb(); { list = _web.Lists[sListName]; _web.AllowUnsafeUpdates = true;
 _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.ToSt开发者_Python百科ring();
}

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


_web = site.OpenWeb();

Shouldn't it be _web = _site.OpenWeb();


Try to add item using SPQuery, like:

   public static SPListItem OptimizedAddItem(SPList list)
   {
       const string EmptyQuery = "0";
       SPQuery q = new SPQuery { Query = EmptyQuery };
       return list.GetItems(q).Add();
   }


You could get ArgumentNullException if

  • CurrentUser is null
  • sConfiguration is null

And you must write code like this:

             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;
                 }
             }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号