我正在尝试向Repeater中的RadioButtonList动态添加RequiredFieldValidator,但它失败并显示错误:
Unable to find control id 'rblAccessory_40' referenced by the 'ControlToValidate' property of ''.
此部分的代码是:
if ((e.Item.ItemType != ListItemType.Header) && (e.Item.ItemType != ListItemType.Footer))
{
Label lblAccID = (Label)e.Item.FindControl("lblAccID");
RadioButtonList rblCondition = (RadioButtonList)e.Item.FindControl("rblCondition");
rblCondition.ID = "rblAccessory_" + lblAccID.Text;
if (conditionList.Count() > 0)
{
RequiredFieldValidator rfv = new RequiredFieldValidator();
rfv.ControlToValidate = "rblAccessory_" + lblAccID.Text;
rfv.ErrorMessage = "Please complete the accessories section";
pnlValidation.Controls.Add(rfv);
rblCondition.DataSource = conditionList;
rblCondition.DataValueField = "id";
rblCondition.DataBind();
}
foreach (ListItem li in rblCondition.Items)
{
li.Text = "";
li.Value = "AccessoryID_" + lblAccID.Text + "-ConditionID_" + li.Value;
}
}
}
肯定会找到RadioButtonList(rblCondition),因为此时数据绑定正确:
rblCondition.DataSource = conditionList;
rblCondition.DataValueField = "id";
rblCondition.DataBind();
所以我不明白为什么错误说无法找到控件ID。
我已尝试手动指定控件ID,如下所示:
rfv.ControlToValidate = "rblAccessory_" + lblAccID.Text;
并且还尝试过:
rfv.ControlToValidate = rblCondition.ID;
lblAccID是一个隐藏文本字段,用于存储转发器中行的ID。
答案 0 :(得分:2)
ItemCreated
事件之后将控件分配给validate属性。我知道这听起来很奇怪,你怎么还能引用动态创建的控件呢?我通过保留对List<Action>
引用的引用来解决这个问题,我将在ItemCreated
期间添加内容以便稍后执行。在您的控件类中,您将声明您的List<Action>
对象:
List<Action> deferringControlToValidateUntilPreRender = new List<Action>();
在ItemCreated
事件中,您将看到一行:
deferringControlToValidateUntilPreRender.Add(() => rfv.ControlToValidate = rblCondition.UniqueID);
然后,也许在PreRender
:
foreach(var deferredAction in deferringControlToValidateUntilPreRender) action();
答案 1 :(得分:0)
由于RequiredFieldValidator
是客户端代码,因此您需要使用控件的客户端ID。像这样:
rfv.ControlToValidate = rblCondition.ClientID;
如果您感兴趣,可以从MSDN获取更多信息:
另外,关于ClientID和UniqueID之间差异的SO讨论(在@MushinNoShin的答案中引用,恕我直言,这是不正确的):