我用这个代码做错了什么
本文关键字:错了 什么 代码 | 更新日期: 2023-09-27 18:27:33
我写了这段代码,我正试图找出我在customValidator上做错了什么,但我得到了这个错误。有人能帮我吗。
在我的表单中,中继器中有许多单选按钮,我根据数据库中的一些唯一字段生成radioButton.ID。属于同一类别的单选按钮被赋予相同的GroupName,如下所示:(因此,我的逻辑是,即使选择了该组的一个单选按钮,也会验证该组)enter code here
radioButton.GroupName = dataRowTemp["QuestionID"].ToString() + dataRowTemp["ControlID"].ToString();
我在.aspx.cs文件后面的代码中有以下代码
CustomValidator customValidator = new CustomValidator();
customValidator.ControlToValidate = radioButton.ID;
customValidator.ClientValidationFunction = "checkRadiobuttonSelection";
customValidator.ValidateEmptyText = true;
customValidator.EnableClientScript = true;
e.Item.Controls.Add(customValidator);
我在.aspx文件中有以下代码
<script type="text/javascript">
function checkRadiobuttonSelection(oSrc, args) {
args.IsValid = false;
var element;
var element2;
var ctrlid = oSrc.id;
var validatorid = document.getElementById(ctrlid);
ctrlid = validatorid.controltovalidate;
element2 = document.getElementById(ctrlid);
for (var i = 0; i < document.forms[0].elements.length; i++) {
element = document.forms[0].elements[i];
if (element.type == "radio") {
if (element.GroupName == element2.GroupName) {
if (element.checked == true) {
args.IsValid = true;
}
}
}
}
}
</script>
当我执行代码时,我得到这个错误
[HttpException (0x80004005): Control '1' referenced by the ControlToValidate property of '' cannot be validated.]
System.Web.UI.WebControls.BaseValidator.CheckControlValidationProperty(String name, String propertyName) +8757509
System.Web.UI.WebControls.CustomValidator.ControlPropertiesValid() +35
System.Web.UI.WebControls.BaseValidator.get_PropertiesValid() +21
System.Web.UI.WebControls.BaseValidator.OnPreRender(EventArgs e) +27
System.Web.UI.Control.PreRenderRecursiveInternal() +80
System.Web.UI.Control.PreRenderRecursiveInternal() +171
System.Web.UI.Control.PreRenderRecursiveInternal() +171
System.Web.UI.Control.PreRenderRecursiveInternal() +171
System.Web.UI.Control.PreRenderRecursiveInternal() +171
System.Web.UI.Control.PreRenderRecursiveInternal() +171
System.Web.UI.Control.PreRenderRecursiveInternal() +171
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +842
有什么建议吗?非常感谢。
我有一个类似的文本框代码,它运行良好,可以整齐地验证文本框。
文本框代码,工作良好
.aspx.cs
CustomValidator customValidator = new CustomValidator();
customValidator.ControlToValidate = textBox.ID;
customValidator.ClientValidationFunction = "changeColorofTextBox";
customValidator.ValidateEmptyText = true;
customValidator.EnableClientScript = true;
e.Item.Controls.Add(customValidator);
.aspx
<script type="text/javascript">
function changeColorofTextBox(oSrc, args) {
if (args.Value.length > 0) {
args.IsValid = true;
}
else {
var ctrlid = oSrc.id;
var validatorid = document.getElementById(ctrlid);
ctrlid = validatorid.controltovalidate;
document.getElementById(ctrlid).style.backgroundColor = "Tomato";
args.IsValid = false;
}
}
</script>
您不能将ControlToValidate与单选按钮一起使用。您需要考虑创建一个自定义验证器,这个答案应该会有所帮助。