Search code examples
c#asp.netpostbackimagebutton

Onclick of ImageButton in asp.net is not working


OnClick event of ImageButton is not working in asp.net. This question has been asked here but all the answers do not work for me. In my case the only difference is I don't have UpdatePanel on my page.

My HTML is as follows:

<ul>
    <asp:DataList ID="PhotoGalleryDataList" runat="server" RepeatColumns="2">
        <ItemTemplate>
            <li><a href="#">
            <div>
               <span>
                  <asp:Label ID="idlabel" runat="server" Text='<%#Eval("AdPhotoID") %>'></asp:Label>
                   <asp:ImageButton ID="AdGallaryImageButton" runat="server" ToolTip="View Photo" CssClass="AdPhotoGallery"
                        AlternateText="Photo" CausesValidation="false" ImageUrl='<%#string.Format("data:image/jpg;base64,{0}",Convert.ToBase64String((byte[])Eval("NormalImage"))) %>'
                        OnClick="AdGallaryImageButton_Click" CommandArgument='<%#Eval("AdPhotoID")%>' />
                </span>
            </div>
            </a></li>
         </ItemTemplate>
    </asp:DataList>
</ul>

In the code-behind, I'm binding like this:

PhotoGalleryDataList.DataSource = dt1;
PhotoGalleryDataList.DataBind();

In dt1 I have NormalImage, IsProfileImage and AdPhotoID, where NormalImage is a byte array and IsProfileImage is Byte and AdPhotoID is varchar(15).

In OnClick event handler of the ImageButton I have:

protected void AdGallaryImageButton_Click(object sender, ImageClickEventArgs e)
{
    // breakpoint here does not get hit
}

Solution

  • In data bound controls like DataList or Repeater you should use OnCommand event to handle clicks:

    <asp:ImageButton ID="AdGallaryImageButton" runat="server" ToolTip="View Photo" CssClass="AdPhotoGallery"
            AlternateText="Photo" CausesValidation="false" ImageUrl='<%#string.Format("data:image/jpg;base64,{0}",Convert.ToBase64String((byte[])Eval("NormalImage"))) %>'
            OnCommand="AdGallaryImageButton_Click" CommandArgument='<%#Eval("AdPhotoID")%>' />
    

    And change the signature of your event handler:

    protected void AdGallaryImageButton_Click(object sender, CommandEventArgs e)
    {
        // Here you can access AdPhotoID argument via e.CommandArgument property
    }