0

I have created an Event Receiver, which is a An item was added type; In my list I have a column called Fotografia it is a Publishing Image type;

In my site-assets library I have an Image called DefImg image could be founded in this: ~/SiteAssets/DefImg.png

In my Event Reciever I have the following code:

public override void ItemAdded(SPItemEventProperties properties)
    {
        base.ItemAdded(properties);


        base.ItemAdded(properties);
        using (SPWeb web = properties.OpenWeb())
        {
            try
            {
                SPListItem currentItem = properties.ListItem;
                if (currentItem["Fotografia"] == null)
                {
                    currentItem["Fotografia"] = "~/SiteAssets/DefImg.png";
                }
                currentItem.Update();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }

How Can I set currentItem["Fotografia"] to the image that could be found in Site Assets Library?

0

If I remember correctly, it should be like that:

    ImageFieldValue imgField = new ImageFieldValue();
    imgField.ImageUrl = "/SiteAssets/DefImg.png";
    currentItem["Fotografia"] = imgField;

I also found this code online that can be helpful:

class Program
{
 static void Main(string[] args)
 {
  try
  {
    using (SPSite site = new SPSite("http://yoursite"))
    {
      using (SPWeb web = site.RootWeb)
      {
        if (PublishingWeb.IsPublishingWeb(web))
        {
          PublishingWeb _pweb = PublishingWeb.GetPublishingWeb(web);
          if (_pweb != null)
          {
            if (_pweb.DefaultPage.Level != SPFileLevel.Checkout)
            {
             if (_pweb.DefaultPage.Item[FieldId.PublishingPageImage] as  ImageFieldValue == null)
             {
               _pweb.DefaultPage.CheckOut();
               ImageFieldValue _field = new ImageFieldValue();
               _field.ImageUrl = "/SiteCollectionImages/home.gif";

                                          _pweb.DefaultPage.Item[FieldId.PublishingPageImage] = _field;
            _pweb.DefaultPage.Item.Update();
            _pweb.DefaultPage.CheckIn("Added Image");
            if (_pweb.PagesList.EnableMinorVersions)
            {
              _pweb.DefaultPage.Publish("Published");
             }
           if (_pweb.PagesList.EnableModeration)
           {
             _pweb.DefaultPage.Approve("Approved!!");
           }

              Console.WriteLine("Image Added");
          }

         }
        }
       }
      }
     }
    }
    catch (Exception ex)
    {
      Console.WriteLine("Error :" + ex.Message);
    }

       Console.ReadLine();
    }
  }
  • It is working perfectly thank you so much I owe you a beer – Nderon Hyseni May 13 '16 at 12:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.