Search code examples
asp.netuser-controlsparameter-passingascx

Need to reference Usercontrol(ascx) in ASPX page in more than one place with different results


Scenario : Default.aspx is as below.

<%@ Page MasterPageFile="~/StandardLayout.master" Language="C#" CodeFile="Default.aspx.cs"     Inherits="_Default" %>
<%@ Register src=  "~/Controls/Us.ascx" tagname="AboutUs" tagprefix="site" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="Server">
    <div id="large">
       <site:AboutUs  ID="AboutUsControl" runat="server" />
    </div>
   <div id="small">
      <site:AboutUs  ID="AboutUsControl" runat="server" />
    </div>
</asp:Content>

AboutUs.ascx.cs assigns some value to a label control. In the above scenario, I want to re-use AboutUs within "div id=small" as the logic is same but only value change.

My question is within AboutUs.ascx.cs, I need some way to find out if it belongs within "", assign Label1 = "I am here". Otherwise Label1 = "I am everywhere"

I am trying to pass parameters but do I need to anything in the code-behind in default.aspx.cs? or any other suggestions.

Please suggest.


Solution

  • Make sure both user controls have unique ID's. I'll use AboutUsControl1 and AboutUsControl2. Declare a name property for your user control:

    private string _doWhat;
        public string doWhat
        {
            get { return _doWhat; }
            set { _doWhat = value; }
        }
    
        //Execute the check somewhere in your code to set the text you want.    
        private void Do_Something()
        {
            if (_doWhat == "Large")
            {
                //display "I am here"
            }
            else
            {
                //display "I am everywhere"
            }
        }
    

    And in the code behind on the page using the user controls, just pass the value by calling the public variable:

    AboutUsControl1.doWhat = "Large";
            AboutUsControl2.doWhat = "Small";
    

    or just set doWhat in the control itself:

    <site:AboutUs ID="AboutUsControl1" runat="server" doWhat="Large" />
    <site:AboutUs ID="AboutUsControl2" runat="server" doWhat="Small" />