Accessing asp.net controls of datalist in codebehind

假装没事ソ 提交于 2019-12-10 12:07:42

问题


I am trying to access an asp Image tag in my code behind so that I can display a default image if there is no other image present. The problem that I am having is that I am getting an "Object reference not set to an instance of an object." error message. The aspx page

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="MemberProfileList.ascx.cs"
Inherits="UserControls_MemberProfileList" %>
<%--<asp:GridView ID="GridView1" runat="server">
</asp:GridView>--%>
<asp:DataList ID="profilelist" runat="server" RepeatColumns="2" OnDataBinding="profilelist_DataBound" >
<ItemTemplate>
    <asp:Image ID="ProfileImage"  runat="server" ImageUrl='<%# System.String.Format("/Images/{0}", DataBinder.Eval(Container.DataItem, "ProfilePictureThumb"))%>'  />
    <asp:Hyperlink runat="server" NavigateUrl='<%#Link.ToSpecificMemberProfile(Eval("Username").ToString()) %>' Text='<%#HttpUtility.HtmlDecode(Eval("Username").ToString()) %>' />
</ItemTemplate>
</asp:DataList>

The method in the code behind

profilelist.DataSource = myProfileList;
    profilelist.DataBind();
    Image ProfileImage = profilelist.FindControl("ProfileImage") as Image;
    string profilepic = ProfileImage.ImageUrl.ToString();
    if (profilepic == null)
    {
        ProfileImage.Visible = false;
    }

Any help is appreciated


回答1:


The Image will be inside an Item, not on the whole List. Implement your logic inside the ItemDataBound event.

Check this out: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.datalist.itemdatabound.aspx

Regards




回答2:


//if you're trying to hide it base on weather the ProfilePictureThumb is Null by putting:**

    <asp:Image ID="ProfileImage" Visible='<%# String.IsNullOrEmpty(Eval("ProfilePictureThumb").ToString())? false:true %>'  runat="server"   ImageUrl='<%# System.String.Format("/Images/{0}", DataBinder.Eval(Container.DataItem, "ProfilePictureThumb"))%>'  />

//if you want to make it display a default image based on weather or not ProfilePicture is null:

    ImageUrl='<%# String.IsNullOrEmpty(Eval("ProfilePictureThumb").ToString())? System.String.Format("/Images/{0}", "defaultimage.jpg"):System.String.Format("/Images/{0}", DataBinder.Eval(Container.DataItem, "ProfilePictureThumb"))%>'

//that way you don't need code behind. 


来源:https://stackoverflow.com/questions/11266138/accessing-asp-net-controls-of-datalist-in-codebehind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!