27

Supposing I have a user control like this

<MyTag:MyWidget runat="server" />

I am wondering if I can do something like

<MyTag:MyWidget runat="server" MemberHeight="400" PublicHeight="200" />

So that in MyWidget.ascx I can have

<div height="<%=IsLoggedIn ? MemberHeight : PublicHeight%>">

or something like that...? Because I want the height to vary in each page that is using this widget.

Răzvan Flavius Panda
  • 21,730
  • 17
  • 111
  • 169
Aximili
  • 28,626
  • 56
  • 157
  • 216
  • 1
    Have you tried it? It is possible to expose public properties in your UserControl that you can set like if it would be a standard property of UserControl(like Visible) in the aspx markup. These properties must be serializable(f.e. String or Integer). – Tim Schmelter Mar 08 '11 at 23:15

2 Answers2

36

Add a public property to the UserControl class something like...

 public int MySize { get; set; }
Steve Wellens
  • 20,506
  • 2
  • 28
  • 69
  • 1
    This is the correct answer (though in your case, you'll add two properties named MemberHeight and PublicHeight). – Jacob Mar 08 '11 at 23:16
  • Seems it's not working if u declare the property as protected. do u know why? – fengd Apr 21 '11 at 19:34
  • @Jun1st - `protected` means that only extending classes can access that Property. In this case, it is a different page/control which needs to access the Property. – Jesse Webb Apr 17 '12 at 19:08
  • 1
    at what moment `MySize` property can be accessed, id it binds in aspx page? mean that in `UserControl.Page_Load` method property == null, so where can it be used? – Roar Jul 21 '14 at 12:50
  • @Roar Did you find the answer to this? – Kristopher Mar 28 '17 at 16:29
  • How do you add a custom property which will trigger a file selector once used within the aspx markup (just like src attribute for image tags, etc.) ? – Ishikawa Dec 22 '20 at 11:37
16

You need to define public properties for both items, as such:

public int MemberHeight{ get; set; }
public int PublicHeight{ get; set; }
Răzvan Flavius Panda
  • 21,730
  • 17
  • 111
  • 169
longhairedsi
  • 3,133
  • 2
  • 28
  • 28