Required property in custom ASP.NET Control

I am creating a custom web control for my ASP page that inherits from CompositeDataBoundControl. I have a public property in the definition of my control, which is required if the user does not provide this property in the definition of the control on the ASP page, it will break and we will get an exception. I want the compiler to issue a warning similar to the one that the user forgets to provide the "runat" property of the control.

"Validation (ASP.Net): Element 'asp: Button' missing required attribute 'runat'."

This is what my code looks like:

public class MyControl : CompositeDataBoundControl, IPostBackEventHandler { private string _someString; public string SomeString { get { return _someString; } set { _someString = value; } } // Other Control Properties, Functions, Events, etc. } 

I want "SomeString" to be the required property and throw a compiler warning when creating my page.

I tried to put the Required attribute above the property as follows:

 [Required] public string SomeString { get { return _someString; } set { _someString = value; } } 

but this does not seem to work.

How can I generate such a compiler message?

+4
source share
1 answer

It is quite simple, when loading the page you can check if the property has any value or not. You can check it for Null or Empty, depending on your type of property. for example if i have this

 private string _someString; public string SomeString { get { return _someString; } set { _someString = value; } } 

In the page_load event, I will check

 if(_someString != null && _someString != "") { String message = "Missing someString property"; isAllPropertySet = false; //This is boolean variable that will decide whether any property is not left un-initialised } 

All the best.

and finally

0
source

All Articles