如何在gridview文本框中添加验证?

时间:2013-10-17 09:46:34

标签: asp.net c#-4.0

<asp:TemplateField HeaderText="Quantity">
    <ItemTemplate>
        <asp:Label ID="lbl_quantity" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"quantity") %>'>
        </asp:Label>

    </ItemTemplate>

    <EditItemTemplate>
        <asp:TextBox runat="server" ID="txtquantity" Width="90px" onkeypress="return validatenumerics(event);" Text='<%# DataBinder.Eval(Container.DataItem,"quantity") %>'></asp:TextBox>
        <asp:RequiredFieldValidator ID="RFquantity" runat="server" ControlToValidate="txtquntity" Display="None" ErrorMessage="This field is required value" ValidationGroup="quantity">
        </asp:RequiredFieldValidator>
        <ajaxToolkit:ValidatorCalloutExtender ID="VCquantity" runat="Server" TargetControlID="RFquantity"/>

    </EditItemTemplate>
</asp:TemplateField>

我想显示一条javascript消息,如果文本框为空,我试过这段代码。为了验证目的,增加了必要的字段验证。然后编辑&#34;按钮没有被解雇..请帮助我。

这是我的网格,包含编辑,更新,取消和取消按钮

  protected void gvproducts_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
    gvproducts.EditIndex = -1;
    grid();

}
protected void gvproducts_RowEditing(object sender, GridViewEditEventArgs e)
{
    gvproducts.EditIndex = e.NewEditIndex;
    grid();
}
protected void gvproducts_RowUpdating(object sender, GridViewUpdateEventArgs e)
{

    TextBox txtquantity = (TextBox)gvproducts.Rows[e.RowIndex].Cells[4].Controls[1];

    int st = Convert.ToInt32(gvproducts.DataKeys[e.RowIndex].Values[0].ToString());


    objsupplyPL.quantity = Convert.ToInt32(txtquantity.Text.ToString());

    objsupplyPL.sno = st;
    DataTable scmpurchase = new DataTable();
    scmpurchase = objsupplyBAL.updatepurchase(objsupplyPL);

    ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "UpdateDetails", "alert('Update Successful');", true);
    gvproducts.EditIndex = -1;
    grid();
}

2 个答案:

答案 0 :(得分:1)

你可以做的是在GridView上方添加一个带有ShowMessageBox的ValidationSummery和一个ValidationGroup

<asp:ValidationSummary ID="ValidationSummary1" runat="server" ShowMessageBox="true" ShowSummary="false" ValidationGroup="quantity" />

将TemplateField更改为此(确保EnableClientScript = true)并确保EditButton具有相同的验证组

<asp:TemplateField HeaderText="Quantity">
    <ItemTemplate>
        <asp:Label ID="lbl_quantity" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"quantity") %>' />
    </ItemTemplate>
    <EditItemTemplate>
        <asp:TextBox runat="server" ID="txtquantity" Width="90px" Text='<%# DataBinder.Eval(Container.DataItem,"quantity") %>' ValidationGroup="quantity"  />
        <asp:RequiredFieldValidator ID="RFquantity" runat="server" ControlToValidate="txtquantity" EnableClientScript="true"  Display="None" ErrorMessage="This field is required value" ValidationGroup="quantity" />
    </EditItemTemplate>
</asp:TemplateField>        
<asp:CommandField ShowEditButton="True" ValidationGroup="quantity" />

答案 1 :(得分:1)

只需在TextBox中添加一个类,然后使用带有jquery的类查找程序找到该控件。然后,您可以使用javascript函数检查TextBox.val()是否为空。