locked
Required properties in custom and web user controls RRS feed

  • Question

  • User251781917 posted

    How can I make a property in a custom control or web user control required, so that if that property is not set by the developer when using the control in a page, a compilation error occurs?

    Thanks! 

    Tuesday, March 25, 2008 2:06 PM

Answers

  • User1872602287 posted

    Aggiekevin,

     You can use a preprocessor directive to trigger a compile-time error when a value is not defined for the property of the control.

    private string myProperty; 

    public string MyProperty

    {

    get

    {

    return this.myProperty;

    }

    set

    {

    this.myProperty = value;

    }

    In this case, I overrode the RenderContents method of the control and added a check of the property. This example will generate an error if you compile a page with the control if the value of the property (in this case a string) is null/empty:

    protected override void RenderContents(HtmlTextWriter writer)

    {

    (other code to render the control's output here)...

    if (string.IsNullOrEmpty(this.MyProperty))

    {

    #error - You must define a value for the MyProperty property!

    }

    }

     

    Hope this helps!

     Jon

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, March 27, 2008 4:34 PM

All replies

  • User-16411453 posted

     Why not just check if the property exist, and if not, write to the screen, you must set the property

     

     
    If [CssClass] Is string.Empty Then
    
    writer.Write("Set the Css")
    
    Exit 
    
    End If 
     

     

    Tuesday, March 25, 2008 2:50 PM
  • User251781917 posted

    Because I don't want to have to wait until run-time to figure out something was not configured properly. 

    Tuesday, March 25, 2008 6:56 PM
  • User1872602287 posted

    Aggiekevin,

     You can use a preprocessor directive to trigger a compile-time error when a value is not defined for the property of the control.

    private string myProperty; 

    public string MyProperty

    {

    get

    {

    return this.myProperty;

    }

    set

    {

    this.myProperty = value;

    }

    In this case, I overrode the RenderContents method of the control and added a check of the property. This example will generate an error if you compile a page with the control if the value of the property (in this case a string) is null/empty:

    protected override void RenderContents(HtmlTextWriter writer)

    {

    (other code to render the control's output here)...

    if (string.IsNullOrEmpty(this.MyProperty))

    {

    #error - You must define a value for the MyProperty property!

    }

    }

     

    Hope this helps!

     Jon

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, March 27, 2008 4:34 PM