首先给一个常规的动态创建控件,并进行验证的代码
[前端aspx代码]
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" %>
[后端Cs代码]
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Test : System.Web.UI.Page
{
private void Page_Load(object sender, System.EventArgs e)
{
}
protected void btnAddControl_Click(object sender, EventArgs e)
{
TextBox _TxtBox = new TextBox();//动态创建一个TextBox
_TxtBox.ID = "TextBox1";
RequiredFieldValidator _Require = new RequiredFieldValidator();//动态创建一个验证控件
_Require.ErrorMessage = "请输入";
_Require.SetFocusOnError = true;
_Require.ControlToValidate = _TxtBox.ID;
TableCell Cell = new TableCell();
Cell.Controls.Add(_TxtBox);
Cell.Controls.Add(_Require);//将刚才创建的二个控件,加入Cell
TableRow Row = new TableRow();
Row.Controls.Add(Cell);
this.Table1.Rows.Add(Row);
btnValidator.Enabled = true;
}
}
运行测试,点击"动态创建控件"后,再点击"验证动态控件",验证控件起作用了,一切正常
接下来,我们加入Ajax环境[加入UpdatePanel控件],将前端代码改为:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" %>
再次运行,发现没办法再对动态生成的控件进行验证了(也就是说,新创建的验证控件没起作用) ,怎么办呢?难道就这样放弃?经过一番尝试,发现了一个很有趣的解决办法,具体参看以下代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" %>
注意上面蓝色的代码,再次运行,哈哈,居然可以了!



