当文本框中需要验证时无法在 gridview 中更新

unable to update in gridview when require validation occur in textbox

我想通过更新命令修改 gridview 中的项目,但在同一页面中我还有一个需要验证的文本框。

当文本框控件中需要验证时,我无法在 gridview 中更新

源代码在这里...

 <div class="row">
    <asp:Button ID="Button1" runat="server" CssClass="btn btn-primary" Text="Add" OnClick="Button1_Click"
        ValidationGroup="btn" />
    <asp:Button ID="Button2" runat="server" CssClass="btn btn-primary" Text="Reset" OnClick="Button2_Click"
        CausesValidation="False" />
    <asp:Button ID="Button3" runat="server" CssClass="btn btn-primary" Text="Show" CausesValidation="False"
        OnClick="Button3_Click" />
</div>
</form> </div> </div>
<asp:GridView ID="GridView1" runat="server" CssClass="table-hover table-responsive table-condensed table-bordered"
    AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="id"
    DataSourceID="SqlDataSource1" Visible="False">
    <Columns>
        <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
        <asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True"
            SortExpression="id" />
        <asp:BoundField DataField="Loc" HeaderText="Location" SortExpression="Loc" />
    </Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:mycon %>"
    SelectCommand="SELECT * FROM [location]" DeleteCommand="Delete From Location Where Id=@id"
    UpdateCommand="update  location set loc=@loc where id=@id">
    <DeleteParameters>
        <asp:ControlParameter ControlID="TextBox1" Name="id" PropertyName="Text" />
    </DeleteParameters>
    <UpdateParameters>
        <asp:Parameter Name="loc" />
        <asp:ControlParameter ControlID="GridView1" Name="id" PropertyName="SelectedValue" />
    </UpdateParameters>
</asp:SqlDataSource>

这里是cs代码

protected void Button1_Click(object sender, EventArgs e)
{
    string qry = "insert into location (loc)values(@loc) ";
    SqlConnection con = Connection.Getconnection();
    con.Open();
    SqlCommand cmd = new SqlCommand(qry, con);
    cmd.Parameters.AddWithValue("@loc", TextBox1.Text);
    int x = cmd.ExecuteNonQuery();
    if (x > 0)
    {
        ClientScript.RegisterStartupScript(Page.GetType(), "validation!", "<script>alert('Successfully Add')</script>");
    }
    else
    {
        ClientScript.RegisterStartupScript(Page.GetType(), "validation!", "<script>alert('Error')</script>");
    }
}
protected void Button2_Click(object sender, EventArgs e)
{
    TextBox1.Text = string.Empty;
}
protected void Button3_Click(object sender, EventArgs e)
{
    GridView1.Visible = true;
}
  1. 请尝试为 button1_click 添加 try catch 以捕获异常。
  2. 验证组只有当CausesValidation的值属性设置为true.and时才会生效验证组需要指定一个value 请参考这个Link