access WebControls markable properties in constructor asp net

早过忘川 提交于 2019-12-23 10:49:09

问题


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" .... />  

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/13420320/access-webcontrols-markable-properties-in-constructor-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!