Required Property in Custom ASP .NET Control

大兔子大兔子 提交于 2019-12-10 09:28:02

问题


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

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

Here is basically 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 a required property and throw a compiler warning when I build my page.

I have tried putting a Required attribute above the property like so:

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

but this doesnt seem to work.

How can I generate such a compiler message?


回答1:


Thats quite simple, on page load you can check if the property has some value or not. You can check it for Null or Empty case depending on your property type. like if i have this

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

On page_load event i will check if

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



来源:https://stackoverflow.com/questions/7931915/required-property-in-custom-asp-net-control

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