How To Embed A UserControl In A Repeater

Page ASPX

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
    CodeBehind="ControlInRepeater.aspx.cs" Inherits="com.dereksandbox.ui.Pages.ControlInRepeater" %>

<%@ Register Src="../Controls/EmbeddedControl.ascx" TagName="EmbeddedControl" TagPrefix="uc1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <asp:Repeater ID="Repeater1" runat="server" 
        onitemdatabound="Repeater1_ItemDataBound">
        <ItemTemplate>
            <uc1:EmbeddedControl ID="EmbeddedControl1" runat="server" />
        </ItemTemplate>
    </asp:Repeater>
</asp:Content>

Page Code Behind

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using com.dereksandbox.bl.ServiceManagers;
using com.dereksandbox.bl.Entities;
using com.dereksandbox.ui.Controls;

namespace com.dereksandbox.ui.Pages
{
    public partial class ControlInRepeater : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Repeater1.DataSource = PersonServiceManager.getPeople();
            Repeater1.DataBind();
        }

        protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            
            
            // This event is fired each time a new Person control is created in the repeater

            EmbeddedControl ctrl = (EmbeddedControl)e.Item.FindControl("EmbeddedControl1");
            ctrl.Person = (PersonEntity)e.Item.DataItem;           
           

        }
    }
}

Control ASCX

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="EmbeddedControl.ascx.cs"
    Inherits="com.dereksandbox.ui.Controls.EmbeddedControl" %>
<asp:Label ID="lblName" runat="server" Text="lblName"></asp:Label>
<asp:Label ID="lblWeight" runat="server" Text="lblAge"></asp:Label>
<br />

Control CodeBehind

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using com.dereksandbox.bl.Entities;

namespace com.dereksandbox.ui.Controls
{
    public partial class EmbeddedControl : System.Web.UI.UserControl
    {
        public PersonEntity Person { get; set; }


        protected void Page_Load(object sender, EventArgs e)
        {
            lblName.Text = Person.Name;
            lblWeight.Text = Person.Weight.ToString();
          
        }

      
    }
}
Advertisements

How To Call A Non-Static Page Method From A UserControl

Scenario: You have a user control that sits in a page. The Control has an ImageButton that needs to call a method on the page containing the control.

Basically we want to wire-up the Controls ImageButton Click event on the Page.

To achieve this expose the ImageButton as a property in the UserControl:

using com.froyo.ehap.ui.Pages;

namespace com.froyo.ehap.ui.Controls
{
    public partial class DisplayStepControl : System.Web.UI.UserControl
    {

        public ImageButton JHACreateIntroButton
        {
            get
            {
               // return the ImageButton you have placed on this control 
               return ImageButton1;
            }
        }


    }
}

Then on your page that contains the method that the button needs to call:

    protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.Page.IsPostBack)
            {
                    // Configure and wire up the actions in toolbar display step selection
                    this.ctrlDisplayStepControl.JHACreateJobStepButton.Click += new ImageClickEventHandler(ibCreateJobSteps_Click);
                 
            }
      }

// The page method the control needs access to  
     
        /// <summary>
        /// Handles the Click event of the ibCreateJobSteps control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.ImageClickEventArgs"/> instance containing the event data.</param>
        protected void ibCreateJobSteps_Click(object sender, EventArgs e)
        {
            if (SaveJHA())
            {
                // Send user to next step      
                Server.Transfer("/Pages/CreateJHAJobSteps.aspx");
            }

        }

Passing Parameters To WebControls

ASPX consuming Control:

<%@ Page Language="C#" MasterPageFile="~/lib/mp/Interior.master" Inherits="AEPcomPage"
    Section="Investors" Title="" %>

<%@ Register Src="~/lib/uc/finance/FilingsGridControl.ascx" TagName="FilingsGridControl" TagPrefix="uc2" %>


<script runat="server">
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        
        FilingsGridControl.DataToDisplay = "APCOData";         
        
    }
    
    
</script>

<asp:Content ID="c2" ContentPlaceHolderID="cphCol2"  runat="Server">
    <uc2:FilingsGridControl
        ID="FilingsGridControl1"
        runat="server"
        />
    
   
</asp:Content>

Control

<%@ Control Language="C#" ClassName="FilingsGridControl" %>
<%@ Import Namespace="System.Web.Mail" %>

<script runat="server">
   
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        lblPagingInformation.Text = DataToDisplay;
    }

   static string sDataToDisplay;

    public static string DataToDisplay
    {
        get { return sDataToDisplay; }
        set { sDataToDisplay = value; }
    }   
 ...
..
.       
    

Also see Passing Parameters From Page (aspx) to WebControl (ascx) Where control exists in another project

Easily Absorb Multiple Web Controls Via NameSpace Reference

Instead of having multiple references to separate controls in your pages. You can put all of them under 1 namespace and reference the single NameSpace. This will allow all controls under this namespace to be accessible.

Create the control by adding a new class into the App_Code directory. In the class definition make sure it inherits CompositeControl.

State Web Control DropDown Field

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using AppName.Objects;

/// <summary>
/// Summary description for StateDropDown
/// </summary>


namespace AppName.WebControls.Fields
{
    [ValidationProperty("SelectedValue")]
    public class StateDropDown : CompositeControl
    {

        public StateDropDown() { }


        // Private Properties
        #region Private Properties
        // Controls   
        private DropDownList _DropDownList = new DropDownList();
        private LiteralControl _LitExample = new LiteralControl();

        // Internal Properties (formerly stored in ViewState)
        private bool _IsExampleVisible = true; // Example is visible by default
        private bool _IsRequired = false;
        private string _OverrideExample = "";
        private State.StateType _StateType = State.StateType.All; // Show all states by default
        private string _ValidationGroup = "";
        #endregion
...
..
.

To use this new control or any control under this namespace simply reference the NameSpace directly within your ASPX.

<%@ Page Language="C#" Theme="LightTheme" %>
<%@ Register TagPrefix="fields" Namespace="AppName.WebControls.Fields" %>

<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="AppName.Objects" %>

<script runat="server">
   
    // Protected Properties   
    protected enum PageStateName
    {
        Form,
        Submitted
        ServiceError
    }
</script>
...
..
.

<div class="field">                         
     <fields:StateDropDown ID="DdlState" runat="server" IsRequired="false"></fields:StateDropDown>
</div>


Passing Parameters From Page (aspx) to WebControl (ascx) Where control exists in another project

When a WebControl exists in the same project as the related page you can easily pass params in the Control directive within the page. In the example below we want to pass the StateCode of KY:

<gcl:GreenPricingControl id="GreenPricingControl" runat="server" StateCode="KY"></gcl:GreenPricingControl>

If the WebControl exists outside of the project you must append the following to the page where the WebControl directive sits:


	protected override void OnLoad(EventArgs e) {
		base.OnLoad(e);
        GlobalUserControl2.SetProperty("StateCode", "KY");
	}

And in your WebControl create a property for it to be available:

public string StateCode
    {
        get {
            if (ViewState["StateCode"] == null) { ViewState["StateCode"] = ""; }
            return (string)ViewState["StateCode"];
        }
        set { ViewState["StateCode"] = value; }
    }

RolloverImageButton WebControl (emulates HTML IMG onMouseOver/onMouseOut)

Unlike HTML tags which support onMouseOver and onMouseOut, ASP.NET ImageButton’s do not.

I created a WebControl that overrides some of the default behaviors of the regular ImageButton mimicking the inline JavaScript functionality for onMouseOver and onMouseOut.

WebControl Code:  [RolloverImageButton.cs]

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Utilities.Common.WebControls.Buttons
{
/// <summary>
/// RolloverImageButton emulates the <img> equivelent of onMouseOver and onMouseOut
/// allowing image swapping.
/// </summary>
/// <usage>
/// Static Image:
///      ImageUrl="/global/utilities/lib/images/content/account/bills/pay/btn_PayNowAtBillMatrix.gif"
/// Rollover Image:
///      ImageOverURL="/global/utilities/lib/images/content/account/bills/pay/btn_PayNowAtBillMatrixRO.gif"
/// </usage>

[DefaultProperty("ImageUrl")]
[ToolboxData("<{0}:RolloverImageButton runat=server></{0}:RolloverImageButton>")]
public class RolloverImageButton : ImageButton
{
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]

#region public virtual string ImageOverUrl
public virtual string ImageOverUrl
{
get
{
if (null == ViewState["ImageOverUrl"])
return string.Empty;
else
return Convert.ToString(ViewState["ImageOverUrl"]);
}

set { ViewState["ImageOverUrl"] = value; }

}
#endregion

// Overridden Methods
#region protected override void AddAttributesToRender(HtmlTextWriter writer)
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
writer.AddAttribute("onMouseOver", "this.src='" + base.ResolveClientUrl(ImageOverUrl) + "'");
writer.AddAttribute("onMouseOut", "this.src='" + base.ResolveClientUrl(ImageUrl) + "'");

base.AddAttributesToRender(writer);
}
#endregion

}
}

Directive:


<%@ Register TagPrefix=”XXXbuttons” Namespace=”Utilities.Common.WebControls.Buttons” Assembly=”Utilities.Common” %>

Implementation:


<XXXbuttons:RolloverImageButton ID=”BtnAccept” runat=”server” AlternateText=”Pay bill now at BillMatrix” ImageUrl=”/global/utilities/lib/images/content/account/bills/pay/btn_PayNowAtBillMatrix.gif” ImageOverURL=”/global/utilities/lib/images/content/account/bills/pay/btn_PayNowAtBillMatrixRO.gif” OnClick=”BtnAccept_Click” /> 

Result:

Pay Now At Bill Matrix Rollover

Pay Now At Bill Matrix