Tech Off Thread

3 posts

ASP.Net - UserControl events in a ListView

Back to Forum: Tech Off
  • steinster

    Hi,

    I have a page with a ListView that contains a custom UserControl. The usercontrol have events, but I cant figure out how to subscribe to these events.

    I tried to define in the aspx file without any luck. I've also tried to set in in the PreRender event of the usercontrol, but the event are always null in the usercontrol no matter what I do.

    This is what I got now;

    protected void animalCardControl1_OnPreRender(object sender, EventArgs e) {
    animalCardControl a = (animalCardControl)sender;

    a.DetailsClickedEvent += new animalCardControl.DetailsClickedHandler(animalCardControl1_DetailsClicked);
    a.Thumb = IsCheckBoxList;

    a.LoadAnimal();
    }



    Any suggestions ??

  • adatapost

    Use the  FindControl() Method to receive a reference of UserControl you are using and then register an event.

  • joechung

    It is too late to bind an event handler to a control during the PreRender stage of a page life cycle. Try the Init or InitComplete stage instead.

    Markup:
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
    EnableViewState="false" Inherits="WebApplication1.WebForm1" %> <%@ Register Src="~/AnimalCardControl.ascx" TagName="AnimalCard" TagPrefix="uc" %> <!DOCTYPE html> <html> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <p><asp:Label ID="Label1" runat="server" /></p> <asp:ListView ID="ListView1" runat="server">
    <ItemTemplate> <p><uc:AnimalCard ID="AnimalCard1" runat="server"
    OnDetailsClicked="AnimalCard1_DetailsClicked" /></p> </ItemTemplate> <LayoutTemplate> <asp:PlaceHolder ID="itemPlaceholder" runat="server" /> </LayoutTemplate> </asp:ListView> </form> </body> </html>

    Code-behind:
    namespace WebApplication1
    {
        using System;
        using System.Linq;
        using System.Web.UI.WebControls;
    
        public partial class WebForm1 : System.Web.UI.Page
        {
            protected override void OnInitComplete(EventArgs e)
            {
                base.OnInitComplete(e);
                ListView1.DataSource = Enumerable.Range(1, 10);
                ListView1.DataBind();
            }
    
            protected void AnimalCard1_DetailsClicked(object sender, EventArgs e)
            {
                Label1.Text = DateTime.Now.ToString();
            }
        }
    }
    

Comments closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.