使 ASP 验证程序仅验证一个网格视图行

本文关键字:验证 一个 网格 视图 ASP 程序 | 更新日期: 2023-09-27 17:56:07

我正在为自己制作一个小网站,在这个网站中你可以成为用户。添加用户的那一刻,它就会进入数据库。您还可以在网格视图中查看现有用户,因此当您创建新用户时,它会进入网格视图。但是一个小问题,当我尝试在此网格视图中使用验证器时,它会验证每一行。我需要它来验证一行。有人说了一些关于行 ID 的事情,但我不知道如何做到这一点。

如您所见,我已经尝试了一些使用RowIndex的东西,但无法使其正常工作

任何帮助不胜感激管理.Aspx :

        <asp:GridView runat="server" ID="gridUsers" AutoGenerateColumns="False" DataKeyNames="username" DataSourceID="DSUserList" OnRowCommand="gridUsers_RowCommand">
            <Columns>
                <asp:BoundField DataField="username" HeaderText="Gebruikersnaam" ReadOnly="True" SortExpression="username"></asp:BoundField>
                <asp:BoundField DataField="display_name" HeaderText="Naam" SortExpression="display_name"></asp:BoundField>
                <asp:TemplateField >
                    <ItemTemplate>
                        <asp:Button OnClientClick="ConfirmDeleteAdmin()" Text="Verwijderen" runat="server" id="btnDeleteUser" CommandName="delUser" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"/>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:TextBox runat="server" id="txtChangePassword" />
                       <%-- TODO: Mike: Validators via code --%>
                        <asp:Button OnClientClick="ConfirmChangePassword()" ValidationGroup="vgChangePW" Text="Wachtwoord wijzigen" runat="server" ID="btnChangePassword" CommandName="changePassword" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />  
                     <%-- <asp:RequiredFieldValidator ID="rfChangePassReq" ControlToValidate="<%# String.Format("txtChangePW{0}",((GridViewRow) Container).RowIndex).ToString() %>" ValidationGroup="vgChangePW" runat="server" ErrorMessage="<br/>U heeft geen nieuw wachtwoord ingevoerd"></asp:RequiredFieldValidator>--%>
                    <%-- asp:RegularExpressionValidator ID="rfChangePassReg" ValidationExpression="^(?=.*[A-Z])(?=.*'d)[a-zA-Z'd]{8,}$" ControlToValidate="<%# String.Format("txtChangePW{0}",((GridViewRow) Container).RowIndex).ToString() %>" ValidationGroup="vgChangePW" runat="server" ErrorMessage="<br/>Uw wachtwoord moet uit minimaal 6 tekenen bestaan en moet minimaal 1 hoofdletter en 1 cijfer bevatten"></asp:RegularExpressionValidator>--%>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
         </asp:GridView>

管理.aspx.cs :

protected void btnCreateUser_Click(object sender, EventArgs e)
    {
        try {
        connection.Open();
        } catch (Exception) {}
        String password = txtPassword.Text.Trim();
        password = password != "" ? ProjectManager.GetSHA1HashData(password) : "";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = connection;
        cmd.CommandText = "sp_add_user";
        cmd.Parameters.Add("@username", SqlDbType.NVarChar, 100).Value = txtUsername.Text;
        cmd.Parameters.Add("@password", SqlDbType.NVarChar, 100).Value = password;
        cmd.Parameters.Add("@displayName", SqlDbType.NVarChar, 100).Value = txtDisplayName.Text;
        cmd.Parameters.Add("@return_value", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
        cmd.ExecuteNonQuery();
        int code = int.Parse(cmd.Parameters["@return_value"].Value.ToString());
        if (code == 0)
        {
            lblNewUserStatus.Text = "Gebruiker bestaat al";
            lblNewUserStatus.ForeColor = Color.Red;
        }
        else
        {
            DSUserList.EnableCaching = false;
            gridUsers.DataBind();
            DSUserList.EnableCaching = true;
            lblNewUserStatus.Text = "Gebruiker toegevoegd";
            lblNewUserStatus.ForeColor = Color.Black;
            txtUsername.Text = "";
            txtPassword.Text = "";
            txtDisplayName.Text = "";
        }
        connection.Close();
    }
    protected void gridUsers_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        // Deletes user or changes a password of a user
        if (e.CommandName == "delUser") 
        {
            string confirmValue = Request.Form["delete_admin"];
            if (confirmValue == "Yes") {
                int index = Convert.ToInt32(e.CommandArgument);
                GridViewRow row = gridUsers.Rows[index];
                String usernameToDelete = row.Cells[0].Text;
                try {
                    connection.Open();
                } catch (Exception) { }
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Connection = connection;
                cmd.CommandText = "sp_delete_user";
                cmd.Parameters.Add("@username", SqlDbType.NVarChar, 100).Value = usernameToDelete;
                cmd.Parameters.Add("@return_value", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
                cmd.ExecuteNonQuery();
                int code = int.Parse(cmd.Parameters["@return_value"].Value.ToString());
                if (code == 0) {
                    //Failed
                    lblDelteStatus.Text = "Kan gebruiker admin niet verwijderen";
                    lblDelteStatus.ForeColor = Color.Red;
                } else {
                    // Deleted
                    lblDelteStatus.Text = "Gebruiker verwijderd";
                    lblDelteStatus.ForeColor = Color.Black;
                    // Reload user list
                    DSUserList.EnableCaching = false;
                    gridUsers.DataBind();
                    DSUserList.EnableCaching = true;
                }
                connection.Close();
                if (usernameToDelete == Session["username"].ToString()) {
                    ProjectManager.logout();
                    Page.Response.Redirect(Page.Request.Url.ToString());
                }
            }
        }
        else if (e.CommandName == "changePassword")
        {
            string confirmValue = Request.Form["change_password"];
            if (confirmValue == "Yes") {
                int index = Convert.ToInt32(e.CommandArgument);
                GridViewRow row = gridUsers.Rows[index];
                String username = row.Cells[0].Text;
                TextBox txtPassword = (TextBox)row.Cells[3].FindControl("txtChangePassword");
                String password = txtPassword.Text.Trim();
                password = password != "" ? ProjectManager.GetSHA1HashData(password) : "";

                try {
                    connection.Open();
                } catch (Exception) { }
                cmd.Connection = connection;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "sp_change_password";
                cmd.Parameters.Add("@password", SqlDbType.NVarChar, 100).Value = password;
                cmd.Parameters.Add("@username", SqlDbType.NVarChar, 100).Value = username;
                cmd.Parameters.Add("@return_value", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
                cmd.ExecuteNonQuery();
                int code = int.Parse(cmd.Parameters["@return_value"].Value.ToString());
                if (code == 0) {
                    lblDelteStatus.Text = "Dit wachtwoord is onlangs gebruikt, kies een ander wachtwoord";
                    lblDelteStatus.ForeColor = Color.Red;
                } else if (code == 1) {
                    lblDelteStatus.Text = "Wachtwoord gewijzigd";
                    lblDelteStatus.ForeColor = Color.Black;
                }
                connection.Close();
            }
        }
    }

使 ASP 验证程序仅验证一个网格视图行

在 RowDataBound 事件中尝试一下:

创建一个特定于行的验证组名称

,该名称是某个前缀和行索引的串联,并将其分配给作为验证组一部分的行中的每个验证程序和控件...即:

valGroupName = string.format("vgRow{0}", e.row.rowindex.tostring);
Button btn = e.row.FindControl("btnChangePassword");
btn.ValidationGroup = valGroupName
RequiredFieldValidator vreq = e.row.FindControl("rfChangePassReq");
vreq.ValidationGroup = valGroupName
RegularExpressionValidator vregx =  e.row.FindControl("rfChangePassReg");
vregx.ValidationGroup = valGroupName
...etc...

这样,当您选择要保存的行按钮时,仅应触发特定行的验证。

我不记得了,我现在也无法测试它,但是您可能对连接到RequiredFieldValidator的任何字段都有问题,它可能会阻止发布。 你必须检查一下。 您可能没问题,因为它们将是不同验证组的一部分。