Andy
Andy

Reputation: 7826

Set codebehind public property directly from ascx

I have three usercontrols: usercontrolA, usercontrolB and usercontrolC which all share the same codebehind each having:

<%@ Control Language="c#" AutoEventWireup="True" Codebehind="usercontrolA.ascx.cs" Inherits="usercontrolA" TargetSchema="http://schemas.microsoft.com/intellisense/ie5" %> at the top of the ascx.

In the codebehind file I have a public property called ShowAll.

I know I can set this property when I put the usercontrol on the page e.g.

<uc1:usercontrolB ID="usercontrolB1" runat="server" ShowAll="true" />

However I would like ShowAll to always be set to true on usercontrolB so would rather not have to set it every time it is placed on a page.

I know I can add a script tag to usercontrolB to set ShowAll in Page_Load:

<script runat="server">
    protected void Page_Load(object sender, System.EventArgs e)
    {
        ShowAll = true;
    }
</script>

But want to keep the Page_Load implementation I already have in the codebehind. Is there any other way to set this property automatically for usercontrolB?

Edit: If it's possible I'd like to be able to set this in the ascx rather than in the code behind, so that someone else later on could add usercontrolD and set ShowAll to true for all instances of usercontrolD without needing to get me to modify and recompile the codebehind.

Upvotes: 3

Views: 4899

Answers (2)

Muhammad Akhtar
Muhammad Akhtar

Reputation: 52241

You have to set this in usercontrol class constructor.

public ConstructorClassName()
    {
       ShowAll = true;
    }

here is complete example with code...

public partial class WebUserControl : System.Web.UI.UserControl
{
  public WebUserControl()
  {
    ShowAll = true;
  }
  private bool _showAll;
  public bool ShowAll
  {
    get { return _showAll; }
    set { _showAll = value; }
  }   

  protected void Page_Load(object sender, EventArgs e)
  {
  }
}

I set the default value to true, but you can also pass the value where you add this user control. e.g.

<uc1:usercontrolB ID="usercontrolB1" runat="server" ShowAll="false" />

When this is called, it will overwrite the value to false

Upvotes: 5

Kon
Kon

Reputation: 27441

In your code behind you can check the instance type:

protected void Page_Load(object sender, System.EventArgs e)
{
    if (this is usercontrolB) 
    {
         ShowAll = true;
    }
}

Upvotes: 0

Related Questions