在为CheckBoxList编程创建CustomValidator ServerValidate事件时遇到问题

本文关键字:事件 遇到 问题 ServerValidate CustomValidator CheckBoxList 编程 创建 在为 | 更新日期: 2023-09-27 18:02:12

我试图用c#动态创建一个asp.net CheckBoxListCustomValidator。我似乎有验证器的创建下来很好,但ServerValidate给了我一些麻烦。我在我手动创建的工作良好的单个CustomValidator之后对其进行了建模,所以我不太确定我需要做什么不同的事情。

这是工作完美的手动CustomValidator。这是我的模型:

<asp:CustomValidator ID="CustomV_JobPositions" runat="server" 
     ErrorMessage="Please select at least one job position." 
     OnServerValidate="CustomV_JobPositions_ServerValidate" 
     ValidationGroup="JobPositions" Display="Dynamic" ForeColor="Red">
</asp:CustomValidator>
<asp:CheckBoxList ID="CBL_JobPositions" runat="server" 
     DataSourceID="JobPositionsEntity" DataTextField="JobPosition1" 
     DataValueField="JobPositionID" RepeatColumns="3" Width="100%" 
     OnSelectedIndexChanged="CBL_JobPositions_SelectedIndexChanged" 
     AutoPostBack="True" ValidationGroup="JobPositions">
</asp:CheckBoxList>

和后面的代码:

protected void CustomV_JobPositions_ServerValidate(object source, ServerValidateEventArgs args)
{
    args.IsValid = false;                              // Assume initially that nothing is checked
    foreach (ListItem item in CBL_JobPositions.Items)  // Loop through each list item in the checkbox
    {
        if (item.Selected == true)                     // If at least one item is checked...
        { args.IsValid = true; }                       // ... then mark the whole list as valid...
    }
}

以上都可以正常运行。
然后我尝试动态/编程地复制它:

public CustomValidator CreateDynamicCustomCheckBoxListValidator(string ControlToValidate, string ValidationGroup)
{
    CustomValidator CV = new CustomValidator();                  // Set up a new CustomValidator
    CV.ID = "CustomV_" + ControlToValidate;                      // Set Validator ID with the name of desired control
    CV.ErrorMessage = "At Least One Selection Required";         // ... then set the error message to "at least one selection required"
    CV.ForeColor = System.Drawing.Color.Red;                     // Make the validator error display red
    CV.ValidationGroup = ValidationGroup;                        // Assign this validator to a group
    CV.Display = ValidatorDisplay.Dynamic;                       // Make the validator display dynamically
    CV.ServerValidate += new ServerValidateEventHandler(CustomV_CheckBoxList_ServerValidate);
    return CV;                                                   // Return the completed validator that was just created
}
private void CustomV_CheckBoxList_ServerValidate(object source, ServerValidateEventArgs args)
{
    args.IsValid = false;                        // Assume initially that nothing is checked
    CheckBoxList CBL = (CheckBoxList)source;
    foreach (ListItem item in CBL.Items)         // Loop through each list item in the checkbox
    {
        if (item.Selected == true)               // If at least one item is checked...
        { args.IsValid = true; }                 // ... then mark the whole list as valid...
    }
}

创建CustomValidator似乎没有麻烦,但是当实际执行验证时,它会抛出以下错误:

"无法强制转换类型为'System.Web.UI.WebControls "的对象。CustomValidator'来输入'System.Web.UI.WebControls.CheckBoxList'。"

唯一的问题是我需要循环遍历复选框列表,如果没有强制转换,我就不能对它进行编程以对源代码执行任何操作。例如,下面的代码给了我这个错误:"foreach语句不能操作'object'类型的变量,因为'object'不包含'GetEnumerator'的公共定义"

private void CustomV_CheckBoxList_ServerValidate(object source, ServerValidateEventArgs args)
{
    args.IsValid = false;                       // Assume initially that nothing is checked
    //CheckBoxList CBL = (CheckBoxList)source;
    foreach (ListItem item in source)           // Loop through each list item in the checkbox
    {
        if (item.Selected == true)              // If at least one item is checked...
        { args.IsValid = true; }                // ... then mark the whole list as valid...
    }
}

关于我如何才能得到这个工作/我做错了什么想法?

在为CheckBoxList编程创建CustomValidator ServerValidate事件时遇到问题

这是一个旧的帖子,但是我遇到了一个类似的问题,所以我想我将发布如何解决这个问题。

创建一个继承自CustomValidator的对象,并给它一个名为ControlId的属性:

公共类customvalidatorwithvalidatedcontrolatattributes: CustomValidator{公共字符串ControlId {get;设置;}}

动态创建一个customvalidatorwithvalidatedcontrolatattributes的实例,提供ControlId属性:

var customValidator = new customvalidatorwithvalidatedcontrolatattributes{ID = string.Concat(控件。ID、"_customFieldValidator")EnableClientScript = false,Display = ValidatorDisplay。动态的,ErrorMessage = "Required",CssClass = "error",ControlId =控件。ID};customValidator。

ServerValidate += customValidator_ServerValidate

然后在ServerValidate方法中将对象转换回customvalidatorwithvalidatedcontrolatattributes类,并从ControlId属性访问复选框,然后检查它是否被选中:

    void customValidator_ServerValidate(object source, ServerValidateEventArgs args)
    {
        var customValidator = source as CustomValidatorWithValidatedControlAttributes;
        if (customValidator != null)
        {
            var checkBox = FindControl(customValidator.ControlId) as CheckBox;
            if (checkBox != null)
            {
                args.IsValid = checkBox.Checked;
            }
        }
        args.IsValid = false;
    }