简体   繁体   中英

String.Empty not working on button click

I am trying to clear the form on cancel button click with a function clearForm() that uses String.Empty with each field of the form but this is not working. I am neither getting any error nor getting the expected result.

Here's my design code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AddEmployee.aspx.cs" Inherits="AddEmployee" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Add Employee</title>
<link href="css/Style.css" type="text/css" rel="Stylesheet" />
</head>
<body>
    <form id="form1" runat="server">
    <ajax:ToolkitScriptManager ID="toolkit1" runat="server"></ajax:ToolkitScriptManager>
    <div>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
        <table align="center" class="loginBox">
            <tr>
                <th colspan="2" style="color:White; font-size:medium; padding-bottom:10px;" align="left">Personal Information</th>
            </tr>
            <tr>
                <td>Name:</td>
                <td><asp:TextBox ID="txtName" CssClass="signup_textbox" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="reqName" ControlToValidate="txtName" runat="server" Display="None" ErrorMessage="Name" ></asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td>Address</td>
                <td><asp:TextBox TextMode="MultiLine" Height="40" Width="135" ID="txtAddress" CssClass="signup_textbox" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="reqAdd" ControlToValidate="txtAddress" runat="server" Display="None" ErrorMessage="Address" ></asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td>DoB:</td>
                <td>
                    <asp:TextBox ID="txtDoB" CssClass="signup_textbox cal_box" runat="server" />
                    <ajax:CalendarExtender ID="CalendarExtender1" TargetControlID="txtDoB" Format="dd/MM/yyyy" runat="server"></ajax:CalendarExtender> 
                </td>
            </tr>
            <tr>
                <td>Gender</td>
                <td>
                    <asp:RadioButtonList CssClass="signup_textbox" ID="GenderList" runat="server" RepeatDirection="Horizontal">
                        <asp:ListItem Selected="True">Male</asp:ListItem>
                        <asp:ListItem>Female</asp:ListItem>
                    </asp:RadioButtonList>
                </td>
            </tr>
            <tr>
                <th colspan="2" style="color:White; font-size:medium; padding-bottom:10px;" align="left">Professional Information</th>
            </tr>
            <tr>
                <td>Department:</td>
                <td>
                    <asp:DropDownList ID="ddlDept" CssClass="signup_textbox" runat="server"></asp:DropDownList>
                </td>
            </tr>
            <tr>
                <td>Designation:</td>
                <td><asp:TextBox ID="txtDesig" CssClass="signup_textbox" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="reqDesig" ControlToValidate="txtDesig" runat="server" Display="None" ErrorMessage="Designation" ></asp:RequiredFieldValidator>
                </td>

            </tr>
            <tr>    
                <td>Salary:</td>
                <td><asp:TextBox ID="txtSal" CssClass="signup_textbox" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="reqSal" ControlToValidate="txtSal" runat="server" Display="None" ErrorMessage="Salary" ></asp:RequiredFieldValidator>
                    <asp:RegularExpressionValidator runat="server" id="rexSal" controltovalidate="txtSal" validationexpression="^[0-9]{5}$" errormessage="Salary must be max 5 digits" Display="None" />
                </td>
            </tr>
            <tr>
                <th colspan="2" style="color:White; font-size:medium; padding-bottom:10px;" align="left">Login Information</th>
            </tr>
            <tr>
                <td>Email:</td>
                <td>
                    <asp:TextBox ID="txtEmail" CssClass="signup_textbox" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="reqEmail" ControlToValidate="txtEmail" runat="server" Display="None" ErrorMessage="Email" ></asp:RequiredFieldValidator>
                    <asp:RegularExpressionValidator ID="valEmail" runat="server" ErrorMessage="Invalid Email" ControlToValidate="txtEmail" ValidationExpression="^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$" CssClass="error_msg" Display="none" />
                </td>
            </tr>
            <tr>
                <td>Username:</td>
                <td>
                    <asp:TextBox ID="txtUser" CssClass="signup_textbox" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="reqUser" ControlToValidate="txtUser" runat="server" Display="None" EnableClientScript="true" SetFocusOnError="true" ErrorMessage="Username" ></asp:RequiredFieldValidator>
                    <asp:RegularExpressionValidator ID="RegularExpressionValidator1" Display="None" ControlToValidate="txtUser" ValidationExpression="^[\s\S]{3,}$" runat="server" ErrorMessage="Username must have at least 3 characters required."></asp:RegularExpressionValidator>
                </td>
            </tr>
            <tr>
                <td>Password:</td>
                <td><asp:TextBox ID="txtPass" CssClass="signup_textbox" runat="server" TextMode="Password"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="reqPass" ControlToValidate="txtPass" runat="server" Display="None" EnableClientScript="true" SetFocusOnError="true" ErrorMessage="Password" ></asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>    
                <td>Confirm Password:</td>
                <td><asp:TextBox ID="txtConfPass" CssClass="signup_textbox" runat="server" TextMode="Password"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="reqConfPass" ControlToValidate="txtConfPass" runat="server" Display="None" EnableClientScript="true" SetFocusOnError="true" ErrorMessage="Confirm Password" ></asp:RequiredFieldValidator>
                    <asp:CompareValidator ID="cmpPass" runat="server" ControlToCompare="txtPass" ControlToValidate="txtConfPass" ErrorMessage="Password must match" CssClass="error_msg" Display="None"></asp:CompareValidator>
                </td>
            </tr>
            <tr>
                <td align="center" colspan="2" style="padding:5px;"><span><asp:Button ID="btnRegister" Width="60" runat="server" Text="Register" CssClass="btnLogin" OnClick="btn_AddEmp" /></span>
                                   <span><asp:Button ID="btnClr" Width="60" runat="server" Text="Cancel" CssClass="btnLogin" OnClick="btn_ClearForm" /></span>
                </td>
            </tr>
        </table>
            <asp:Panel ID="errorsPanel" runat="server" Style="display: none; border-style: solid; border-width: thin; border-color: #FFDBCA" Width="175px" BackColor="White">
            <asp:ValidationSummary ID="valSummary" runat="server" CssClass="error_msg" HeaderText="You must enter following" DisplayMode="BulletList" EnableClientScript="true" ShowSummary="true" />
         </asp:Panel>
        </ContentTemplate>
        </asp:UpdatePanel>
            </div>
    </form>
</body>
</html>

Here's my code-behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;

public partial class AddEmployee : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {


    }


    protected void btn_ClearForm(object sender, EventArgs e) //to clear form on IsPostBack or on press of cancel button
    {
        if (!IsPostBack)
        {
            clearForm();
        }
    }

    #region public functions

    public void clearForm()
    {
        txtName.Text = String.Empty;
        txtAddress.Text = String.Empty;
        txtDoB.Text = String.Empty;
        txtDesig.Text = String.Empty;
        txtSal.Text = String.Empty;
        txtEmail.Text = String.Empty;
        txtUser.Text = String.Empty;
        txtPass.Text = String.Empty;
        txtConfPass.Text = String.Empty;
        GenderList.Items[0].Selected = true;
        GenderList.Items[1].Selected = false;
    }

    #endregion

}

There is nothing wrong with string.Empty . But you do not need condition in btn_ClearForm as btn_ClearForm handler will always called on postback and you put the condition if !IsPostBack

// if (!IsPostBack) 
//{
    clearForm();
// }

Your code would be

protected void btn_ClearForm(object sender, EventArgs e) 
{       
        clearForm();       
}

Got the fix!

Just use CausesValidation="false" on the cancel button so as to disable validation upon cancel button click event.

Because when you have used validation on your controls without using CausesValidation="false" on the cancel button, your controls will be forced to pass through validation conditions given to them and since the cancel button is meant to clear your form regardless of checking the validity of the data in form fields, the form will get stuck.

So whenever you have used validation conditions on your controls, just make sure you don't get them fired on the click of Cancel/clear/reset button.

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM