使ASP验证器只验证一个gridview行?

时间:2015-06-12 15:34:26

标签: c# asp.net validation gridview

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

正如你所看到的,我已经尝试过RowIndex的一些东西,但是无法让它工作

感谢任何帮助 Management.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>

Management.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();
            }
        }
    }

1 个答案:

答案 0 :(得分:2)

在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相关联的任何字段的问题,这可能会阻止发布。你必须检查出来。您可能没问题,因为他们将成为不同验证组的一部分。