Search code examples
c#asp.netcode-behinddatalist

Accessing asp.net controls of datalist in codebehind


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


Solution

  • 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