0
votes

I have custom List which has image field. I have to display the image through the object modelling code.

Which Control I need to use to display the image in a webpart and which property I need to assign it for.

[Guid("207cea76-b1ee-4b86-9638-00c22d3d9398")]
public class News : System.Web.UI.WebControls.WebParts.WebPart
{
    Label lblTitle;
    ImageField  imgNews;
    Label lblDescription;
    public News()
    {
    }

    protected override void CreateChildControls()
    {
        base.CreateChildControls();
        lblTitle = new Label();
        imgNews = new ImageField();
        lblDescription = new Label();

        string siteURL = "http://my-dev-box-har";
        using (SPSite site = new SPSite(siteURL))
        {
            using (SPWeb web = site.OpenWeb())
            {
                SPListItemCollection  list = web.Lists["News"].Items ;
                foreach (SPListItem  item in list)
                {
                    lblTitle.Text = item["Title"].ToString();
                    lblDescription.Text = item["Description"].ToString();
                    imgNews. = item[""].ToString();
                    Controls.Add(lblTitle);
                    Controls.Add(lblDescription);
                   }




            }
        }

    }
}

}

I don't know wheather to use image or Imagefield control to display my image form the sharepoint custom list.

Could anybody point me in right direction please.

Thank you Hari

1

1 Answers

1
votes

This is the most simple example I could come up with:

using System.ComponentModel;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;

namespace TestPictureWebPart.PicWebPart
{
    [ToolboxItemAttribute(false)]
    public class PicWebPart : WebPart
    {
        protected override void CreateChildControls()
        {
            SPList list = SPContext.Current.Web.Lists["ImageList"];
            SPListItemCollection items = list.Items;

            foreach (SPListItem item in items)
            {
                string title = item[SPBuiltInFieldId.Title].ToString(); // or string title = item.Title;
                SPFieldUrlValue picture = new SPFieldUrlValue(item["MyPicture"].ToString());

                Image image = new Image();
                image.ToolTip = title;
                image.ImageUrl = picture.Url;
                Controls.Add(image);
            }
        }
    }
}

Just a tip: it's always better to use SPBuiltInFieldId to access out-of-the-box columns in SharePoint.

Also, in your example code... if you have more than one listitem in your list, you are in trouble. You will use the same web controls (the labels for example) for each listitem and add them to the Controls collection in every iteration.