在asp.net转发器中管理图像(为每张图片添加类)

时间:2012-11-03 17:21:02

标签: asp.net webforms

这是我的代码:

代码隐藏:

public class data
....
...

public List<dataImages> Images { get; set; }
...

var data= GarageBLL.LoadData(Convert.ToInt32(DataId), Convert.ToInt32(MemberId));
rptImages.DataSource = data.Images.Take(3);
rptImages.DataBind();

ASPX:

   <asp:Repeater runat="server" ID="rptImages">
        <ItemTemplate>
            <asp:Image runat="server" CssClass="img1" ImageUrl='<%# String.Format("/images/{0}/{1}.{2}", DataId, Eval("ImageId"), Eval("Extension")) %>' />
        </ItemTemplate>
    </asp:Repeater>

所以,这在目前是有效的,但我想为每个图像添加不同的类。 任何人都知道我该怎么做?

1 个答案:

答案 0 :(得分:2)

您可以使用转发器的ItemDataBound事件来设置CssClass

protected void rptImages_ItemDataBound(Object Sender, RepeaterItemEventArgs e) {
      // This event is raised for the header, the footer, separators, and items.
      // Execute the following logic for Items and Alternating Items.
      if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
         dataImages img = (dataImages) e.Item.DataItem;
         Image img1 = (Image) e.Item.FindControl("img1");
         // add your correct logic here according to the dataImages properties
         img.CssClass = "YourCssClass";
         // assuming you just want different classes for your three images, use ItemIndex with remainder:
         string class = "img" + (e.Item.ItemIndex % 3 + 1).ToString() + "class";
         img.CssClass = class;
      }
   }