如果使用自动生成的列,如何将输入验证添加到 Gridview?我有一个包含汽车对象的列表。网格视图绑定到列表。网格视图具有添加和编辑功能。我必须验证车牌等字段。如何使用验证控件执行此操作?
假设您正在谈论在 GridView 处于编辑模式时向其添加验证控件(如CompareValidator
),则可以使用 GridView 的 RowDataBound 事件以编程方式添加验证程序控件:
ASP.NET
<asp:GridView ID="gv" runat="server" OnRowDataBound="gv_RowDataBound"...
C#
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (gv.EditIndex == e.Row.RowIndex)
{
TextBox tb = e.Row.Cells[0].Controls[0] as TextBox; // get reference to your Control to validate (you specify cell and control indeces)
tb.ID = "reg_" + e.Row.RowIndex; // give your Control to validate an ID
CompareValidator cv = new CompareValidator(); // Create validator and configure
cv.Operator = ValidationCompareOperator.GreaterThan;
cv.Type = ValidationDataType.Double;
cv.Display = ValidatorDisplay.Dynamic;
cv.ErrorMessage = "<br/>Not a valid number";
cv.ForeColor = Color.Red;
cv.ControlToValidate = tb.ID;
e.Row.Cells[0].Controls.Add(cv); // Add validator to GridView cell
}
}
}
在您正在编辑的行上,您可以引用要将验证器链接到的控件,例如您的汽车登记TextBox
。然后,您需要给它一个 ID,创建一个验证器并将其ControlToValidate
属性指定为 TextBox
ID,然后将验证器添加到包含您的TextBox
的同一单元格中。
此示例演示如何强制TextBox
仅允许双精度。