Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access WebControls markable properties in constructor asp net

Here is my custom control.It inherits [Height] property from WebControl class.I want to access it in constructor for calculating other properties.But its value is always 0.Any idea?

    public class MyControl : WebControl, IScriptControl
{

    public MyControl()
    {
       AnotherProperty = Calculate(Height);
       .......
    }

my aspx

       <hp:MyControl   Height = "31px" .... />  
like image 997
Anton Putov Avatar asked Oct 06 '22 23:10

Anton Putov


2 Answers

Markup values are not available in your control's constructor but they are available from within your control's OnInit event.

protected override void OnInit(EventArgs e)
{
    // has value even before the base OnInit() method in called
    var height = base.Height;

    base.OnInit(e);
}
like image 122
andleer Avatar answered Oct 10 '22 01:10

andleer


As @andleer said markup has not been read yet in control's constructor, therefore any property values that are specified in markup are not available in constructor. Calculate another property on demand when it is about to be used and make sure that you not use before OnInit:

private int fAnotherPropertyCalculated = false;
private int fAnotherProperty;
public int AnotherProperty
{
  get 
  {
    if (!fAnotherPropertyCalculated)
    {
       fAnotherProperty = Calculate(Height);
       fAnotherPropertyCalculated = true;
    }
    return fAnotherProperty;
  }
}
like image 26
Igor Avatar answered Oct 10 '22 03:10

Igor