带验证的自定义DropDownList

时间:2011-02-02 22:24:00

标签: c# asp.net drop-down-menu

我正在尝试通过创建从DropDownList继承的自定义控件向DropDownList添加验证支持:

public class MyDropDown: DropDownList, INamingContainer
{
    private const string ValidatorID = "Validator";
    private RequiredFieldValidator _validator;

    protected override ControlCollection CreateControlCollection()
    {
        return new ControlCollection(this);
    }

    protected override void CreateChildControls()
    {
        base.CreateChildControls();
        Controls.Clear();

        _validator = new RequiredFieldValidator
        {
            ID = String.Format("{0}_{1}", ID, ValidatorID),
            ControlToValidate = ID,
            InitialValue = String.Empty,
            ErrorMessage = "*",
            ForeColor = Color.Red
        };

        Controls.Add(_validator);
    }

    protected override void Render(HtmlTextWriter writer)
    {
        base.Render(writer);
        _validator.RenderControl(writer);
    }
}

我的类实现 INamingContainer 因为我想避免命名冲突。 不幸的是,当我尝试使用此控件时,我得到以下异常:

  

无法找到'MDD_Validator'的'ControlToValidate'属性引用的控件ID'MDD'

这是因为 INamingContainer FindControl(NamingContainerId)返回null。

当我删除 INamingContainer 实现并以下列方式设置验证器ID时:

_validator.ID = String.Format("{0}_{1}", ID, ValidatorID);

一切正常,并且给予Validator的id与命名容器中的id相同。

但有没有办法完成 WITH INamingContainer?

1 个答案:

答案 0 :(得分:1)

您在下拉控件中有验证器。为了使验证器工作,它需要与要验证的控件位于同一容器中。您需要做的是重新调整类,使DropDownList与RequiredFieldValidator位于同一容器中。我会做这样的事情:

public class MyDropDown: WebControl, INamingContainer
{
    private DropDownList _dropDown;
    private RequiredFieldValidator _validator;

    protected override void CreateChildControls()
    {
        base.CreateChildControls();
        Controls.Clear();

        _dropDown = new DropDownList();
        _dropDown.ID = ID + "_ddl";
        Controls.Add(_dropDown);

        _validator = new RequiredFieldValidator();
        _validator.ID = ID + "_Validator";
        _validator.ControlToValidate = _dropDown.ClientID;
        _validator.InitialValue = String.Empty;
        _validator.ErrorMessage = "*";
        _validator.ForeColor = Color.Red;
        Controls.Add(_validator);
    }

    //etc.
}

信息在这里 http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.basevalidator.controltovalidate.aspx