سؤال

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" .... />  
هل كانت مفيدة؟

المحلول

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);
}

نصائح أخرى

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;
  }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top