使用自动生成的列向gridview添加验证

时间:2012-11-20 20:45:03

标签: c# asp.net gridview

如果使用自动生成的列,如何向Gridview添加输入验证?我有一个包含汽车对象的清单。 gridview绑定到列表。 gridview具有添加和编辑功能。而且我必须验证像登记牌这样的字段。如何使用验证控件来做到这一点?

1 个答案:

答案 0 :(得分:0)

假设您正在讨论在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仅允许双打。