2011-02-11 127 views
0

我有自定義列表中有圖像字段。我必須通過對象建模代碼來顯示圖像。圖像自定義網頁

哪個控件我需要用來在webpart中顯示圖像以及我需要爲其指定哪個屬性。

[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); 
        } 




      } 
     } 

    } 
} 

}

我不知道wheather使用圖像或ImageField的控件來顯示我的形象形成的SharePoint自定義列表。

有人可以指點我正確的方向請。

謝謝 哈日

回答

1

這是最簡單的例子我能想出:

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

只是一個提示:它總是最好使用SPBuiltInFieldId訪問外的開箱SharePoint中的列。

另外,在您的示例代碼中...如果您的列表中有多個listitem,那麼您遇到了麻煩。您將爲每個listitem使用相同的Web控件(例如標籤),並在每次迭代中將它們添加到Controls集合中。