String.Empty not working on button click - c#

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

Related

Update query not firing properly. Update does not reflect

My Code Behind File is UpdatePublication.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
namespace SBAIMS
{
public partial class UpdatePublisher : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["P_Id"] != null)
{
string s = Request.QueryString["P_Id"].ToString();
SqlConnection con = new SqlConnection(#"Data Source=AP\sqlexpress;Initial Catalog=SBAIMS;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select * from Publication_Master where P_Id='" + s + "' ", con);
SqlDataAdapter adptr = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adptr.Fill(ds, "Publication_Master");
if (ds.Tables["Publication_Master"].Rows.Count > 0)
{
upub.Text = ds.Tables["Publication_Master"].Rows[0]["Publication"].ToString();
upname.Text = ds.Tables["Publication_Master"].Rows[0]["Publisher"].ToString();
upc1.Text = ds.Tables["Publication_Master"].Rows[0]["P_Contact"].ToString();
upc2.Text = ds.Tables["Publication_Master"].Rows[0]["P_Contact2"].ToString();
upemail.Text = ds.Tables["Publication_Master"].Rows[0]["P_Email"].ToString();
upban.Text = ds.Tables["Publication_Master"].Rows[0]["P_BankAccount"].ToString();
}
con.Close();
}
}
protected void submitupdatepub_Click(object sender, EventArgs e)
{
string s = Request.QueryString["P_Id"].ToString();
SqlConnection con2 = new SqlConnection(#"Data Source=AP\sqlexpress;Initial Catalog=SBAIMS;Integrated Security=True");
con2.Open();
SqlCommand cmd2 = new SqlCommand("UPDATE Publication_Master SET Publication='" + upub.Text + "', Publisher='" + upname.Text + "', P_Contact='" + upc1.Text + "', P_Contact2='" + upc2.Text + "', P_Email='" + upemail.Text + "', P_BankAccount='" + upban.Text + "' WHERE P_Id='"+s+"'", con2);
cmd2.ExecuteNonQuery();
con2.Close();
Response.Redirect("~/UPublisher.aspx");
}
}
}
My ASPX file is UpdatePublication.aspx
<%# Page Title="Update Publication" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
CodeBehind="UpdatePublication.aspx.cs" Inherits="SBAIMS.UpdatePublisher" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div id="updatepublisher">
<table width="100%" class="table table-borderless table-responsive">
<tr>
<td width="50%" style="vertical-align: top;">
<div class="panel panel-success" id="updatepub">
<div class="panel-heading">
<h4>
<b>Update Publication.</b></h4>
</div>
<div class="panel-body">
<h5>
Update data about Publication.</h5>
<br />
<div align="center">
<asp:Label ID="updatepubsubmit" runat="server" Font-Size="Medium" Text="Update Was Successful !!"
CssClass="alert alert-success alcntr" Visible="False"></asp:Label>
</div>
<br />
<br />
<table class="table table-borderless table-responsive fs15" align="center" style="width: 500px; background-color: transparent;">
<tr>
<td width="40%">
Publication Name
</td>
<td width="60%">
<asp:TextBox ID="upub" CssClass="form-control fs15" autocomplete="off" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator8" runat="server" ErrorMessage="* Field Required"
ControlToValidate="upub" Display="Dynamic" SetFocusOnError="True" Font-Size="Medium"
CssClass="rfvlabel" ValidationGroup="rfvup"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
Publisher (/Distributor) Name
</td>
<td>
<asp:TextBox ID="upname" CssClass="form-control fs15" autocomplete="off" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator9" runat="server" ErrorMessage="* Field Required"
ControlToValidate="upname" Display="Dynamic" SetFocusOnError="True" Font-Size="Medium"
CssClass="rfvlabel" ValidationGroup="rfvup"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator9" runat="server" ErrorMessage="* Enter characters or valid symbols" ControlToValidate="upname" Display="Dynamic" SetFocusOnError="True" Font-Size="Medium"
CssClass="rfvlabel" ValidationExpression="^[a-zA-Z''-'\s]{1,40}$" ValidationGroup="rfvup"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
Contact No. 1
</td>
<td>
<asp:TextBox ID="upc1" CssClass="form-control fs15" autocomplete="off" placeholder="optional" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator10" runat="server" ErrorMessage="* Numbers Only"
ControlToValidate="upc1" Display="Dynamic" SetFocusOnError="True" Font-Size="Medium"
CssClass="rfvlabel" ValidationExpression="^([0-9]*)$" ValidationGroup="rfvup"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
Contact No. 2
</td>
<td>
<asp:TextBox ID="upc2" CssClass="form-control fs15" autocomplete="off" placeholder="optional" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator11" runat="server" ErrorMessage="* Numbers Only"
ControlToValidate="upc2" Display="Dynamic" SetFocusOnError="True" Font-Size="Medium"
CssClass="rfvlabel" ValidationExpression="^([0-9]*)$" ValidationGroup="rfvup"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
Publisher Bank A/C No.
</td>
<td>
<asp:TextBox ID="upban" CssClass="form-control fs15" autocomplete="off" placeholder="optional" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator12" runat="server" ErrorMessage="* Numbers Only"
ControlToValidate="upban" Display="Dynamic" SetFocusOnError="True" Font-Size="Medium"
CssClass="rfvlabel" ValidationExpression="^([0-9]*)$" ValidationGroup="rfvup"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
Pub. Email ID
</td>
<td>
<asp:TextBox ID="upemail" CssClass="form-control fs15" autocomplete="off" placeholder="optional" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator13" runat="server" ErrorMessage="* Please Enter Valid Email ID"
Display="Dynamic" CssClass="rfvlabel" ControlToValidate="upemail" ValidationGroup="rfvup"
ValidationExpression="^([0-9a-zZ-Z]([-.\w]*[0-9a-zA-Z])*#([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$"></asp:RegularExpressionValidator>
</td>
</tr>
</table>
<br />
<table class="table table-borderless table-responsive" align="center" style="width: 300px;
background-color: transparent;">
<tr>
<td colspan="2" align="center">
<asp:Button ID="submitupdatepublisher" runat="server" OnClick="submitupdatepub_Click" class="btn btn-success btn-block"
Font-Size="Large" Text="Update" ValidationGroup="rfvup" />
</td>
</tr>
</table>
</div>
</div>
</td>
<td></td>
</tr>
</table>
</div>
</asp:Content>
The update doesn't work successfully. I mean it does not reflect in database. It just according to code, redirects to the specified page. Please help me where i am going wrong.
Actually the problem is now solved. I thank all of you for your concerns.
The problem was solved by just putting if not postback condition.
if (!Page.IsPostBack)
{
if (Request.QueryString["P_Id"] != null)
{
....
}
}

asp:LinkButton - validate form field

I am completely new to C# and I am trying to figure out form validation.
More specifically, I have a webform (C#) that I've split into to parts "form-part-1" and "form-part-2".
By default "form-part-2" is hidden. Once all fields in "form-part-1" are completed, you should be able to proceed to "form-part-2" by clicking on the "Continue" linkButton.
The jQuery part works well, showing and hiding form sections as desired.
But the validation is not enforced anymore.
I have validators in place but at this point I can proceed to "form-part-2" without filling out the "form-part-1" fields.
I would like the validation to be enforced before proceeding to "form-part-2".
Any tips and suggestions how to do it would be greatly appreciated.
Thanks in advance.
Here's my code:
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#continue").click(function (event) {
$('#form-part-1').hide();
$('#form-part-2').fadeIn();
});
});
</script>
<form id="SignUp" method="post" runat="server">
<table id="validation">
<tr>
<td colspan="2" vAlign="top">
<asp:ValidationSummary ID="vsSignupValidation" runat="server"></asp:ValidationSummary></td>
</tr>
</table>
<table id="form-part-2">
<tr>
<td width="150">
<label class="">
<asp:label id="lblSignupFirstName" Runat="server">First Name:</asp:label>
<span style="color:red">*</span>
</label>
</td>
<td>
<asp:TextBox size="30" CssClass="input" ID="txtSignupFirstName" TabIndex="1" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td width="150">
<label class="">
<asp:label id="lblSignupLastName" Runat="server">Last Name:</asp:label>
<span style="color:red">*</span>
</label>
</td>
<td>
<asp:TextBox size="30" CssClass="input" ID="txtSignupLastName" TabIndex="1" runat="server"></asp:TextBox>
</td>
</tr>
</table>
<!-- validate and continue -->
<asp:LinkButton ID="continue" runat="server" onclientclick="return false;">Continue</asp:LinkButton>
<!-- validate and continue -->
<table id="form-part-1">
<tr>
<td width="150">
<label class="">
<asp:label id="lblSignupUserID" Runat="server">UserID:</asp:label>
<span style="color:red">*</span>
</label>
</td>
<td>
<asp:TextBox size="30" CssClass="input" ID="txtSignupUserID" TabIndex="1" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td width="150">
<label class="">
<asp:label id="lblSignupPassword" Runat="server">Last Name:</asp:label>
<span style="color:red">*</span>
</label>
</td>
<td>
<asp:TextBox size="30" CssClass="input" ID="txtSignupPassword" TabIndex="1" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td width="150">
<label class="">
<asp:Label class="formtxtsm" ID="lblSignupConfirmPassword" runat="server">Confirm password</asp:Label>
<span style="color:red">*</span>
</label></td>
<td>
<asp:TextBox size="30" ID="txtSignupConfirmPassword" TabIndex="10" runat="server" TextMode="Password" CssClass="input"></asp:TextBox>
</td>
</tr>
</table>
<!-- validators -->
<asp:requiredfieldvalidator id="rfvSignupFirstName" runat="server" Display="None" ControlToValidate="txtSignupFirstName" class="formerrortxt" ErrorMessage='"First Name" is required'></asp:requiredfieldvalidator>
<asp:requiredfieldvalidator id="rfvSignupLastName" runat="server" Display="None" ControlToValidate="txtSignupLastName" class="formerrortxt" ErrorMessage='"Last Name" is required'></asp:requiredfieldvalidator>
<asp:RequiredFieldValidator ID="rfvSignupUserID" runat="server" Display="None" ControlToValidate="txtSignupUserID" ErrorMessage='"Username" is required.'></asp:RequiredFieldValidator>
<asp:requiredfieldvalidator id="rfvSignupPassword" runat="server" Display="None" ControlToValidate="txtSignupPassword" ErrorMessage='"Password" is required.'></asp:requiredfieldvalidator>
<asp:requiredfieldvalidator id="rfvSignupConfirmPassword" runat="server" Display="None" ControlToValidate="txtSignupConfirmPassword" ErrorMessage='"Confirm password" is required.'></asp:requiredfieldvalidator>
<asp:customvalidator id="cvSignupPasswordMatch" runat="server" Display="None" ErrorMessage='"Password" and "Confirm password" must match exactly.'></asp:customvalidator>
</form>
**** EDIT:
Thanks Phx & Daniel for your feedback. Very helpful!
I got things working with one exception. The "form-part-2" fields get validated before I even get to the step 2. Any tips how to validate the username / password fields only after I get to the "form-part-2"? Thanks in advance!
here's my most recent version:
www.smithy.somee.com
and the code:
<script language="javascript" type="text/javascript">
$(document).ready(function () {
if (Page_ClientValidate("personalGroup")) {
$('#form-part-1').hide();
$('#form-part-2').fadeIn();
}
if (Page_ClientValidate("accountGroup")) {
$('#form-part-2').hide();
}
});
</script>
<form id="signup" runat="server">
<div>
<table id="validators">
<tr>
<td>
<asp:ValidationSummary ID="personalGroupSummary" runat="server" ValidationGroup="personalGroup" />
<asp:ValidationSummary ID="accountGroupSummary" runat="server" ValidationGroup="accountGroup" />
</td>
</tr>
</table>
<table id="form-part-1">
<tr>
<td>First Name:</td>
<td><asp:TextBox ID="txtFname" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>Last Name:</td>
<td><asp:TextBox ID="txtLname" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="continue" runat="server" causesvalidation="true" validationgroup="personalGroup" Text="Continue" />
</td>
</tr>
</table>
<table id="form-part-2">
<tr>
<td>Username:</td>
<td><asp:TextBox ID="txtUser" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>Password:</td>
<td><asp:TextBox ID="txtPass" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="btnSubmit" runat="server" validationgroup="accountGroup" Text="Submit" OnClick="btnSubmit_Click" />
</td>
</tr>
</table>
<!-- output -->
<table>
<tr>
<td>First: </td>
<td><asp:Label ID="lblFname" runat="server" Text=""></asp:Label></td>
</tr>
<tr>
<td>Last:</td>
<td><asp:Label ID="lblLname" runat="server" Text=""></asp:Label></td>
</tr>
<tr>
<td>User:</td>
<td><asp:Label ID="lblUser" runat="server" Text=""></asp:Label></td>
</tr>
<tr>
<td>Pass:</td>
<td><asp:Label ID="lblPass" runat="server" Text=""></asp:Label></td>
</tr>
</table>
</div>
<!-- validators -->
<asp:requiredfieldvalidator id="fvFname" runat="server" validationgroup="personalGroup" Display="None" ControlToValidate="txtFname" ErrorMessage='"First Name" is required'></asp:requiredfieldvalidator>
<asp:requiredfieldvalidator id="fvLname" runat="server" validationgroup="personalGroup" Display="None" ControlToValidate="txtLname" ErrorMessage='"Last Name" is required'></asp:requiredfieldvalidator>
<asp:requiredfieldvalidator id="fvUser" runat="server" validationgroup="accountGroup" Display="None" ControlToValidate="txtUser" ErrorMessage='"Username" is required'></asp:requiredfieldvalidator>
<asp:requiredfieldvalidator id="fvPass" runat="server" validationgroup="accountGroup" Display="None" ControlToValidate="txtPass" ErrorMessage='"Password" is required'></asp:requiredfieldvalidator>
<!-- validators -->
</form>
As you wrote: I would like the validation to be enforced before proceeding to "form-part-2".
You need to create validations groups in order to validate first N fields and the another N Fields.
So create Validation groups for your controls:
http://msdn.microsoft.com/en-us/library/vstudio/ms227424(v=vs.100).aspx
<asp:textbox id="AgeTextBox"
runat="Server">
</asp:textbox>
<asp:requiredfieldvalidator id="RequiredFieldValidator2"
controltovalidate="AgeTextBox"
validationgroup="PersonalInfoGroup"
errormessage="Enter your age."
runat="Server">
</asp:requiredfieldvalidator>
<!--When Button1 is clicked, only validation
controls that are a part of PersonalInfoGroup
are validated.-->
<asp:button id="Button1"
text="Validate"
causesvalidation="true"
validationgroup="PersonalInfoGroup"
runat="Server" />
<asp:textbox id="CityTextBox"
runat="Server">
</asp:textbox>
<asp:requiredfieldvalidator id="RequiredFieldValidator3"
controltovalidate="CityTextBox"
validationgroup="LocationInfoGroup"
errormessage="Enter a city name."
runat="Server">
</asp:requiredfieldvalidator>
<!--When Button2 is clicked, only validation
controls that are a part of LocationInfoGroup
are validated.-->
<asp:button id="Button2"
text="Validate"
causesvalidation="true"
validationgroup="LocationInfoGroup"
runat="Server" />
Then use a Diferent validation summary for each group.
Perhaps you need a button for each validation but you can do the trick and use the same button for multiple validation groups:
http://www.aspsnippets.com/Articles/Validate-Multiple-Validation-Groups-with-one-Button-in-ASPNet.aspx
Another example here
http://www.codeproject.com/Tips/401611/Validate-multiple-Validation-group-both-client-and
Phx gives a partial answer. Use his suggestion to create ValidationGroups. Put all your validators in part 1 and part 2 in separate groups.
JQuery does not automatically trigger validation.
You need to call the validation manually with your JavaScript. This can be done by calling Page_ClientValidate which will validate all validators for the passed ValidationGroup.
For example:
$("#continue").click(function (event) {
if (Page_ClientValidate("group1")) {
$('#form-part-1').hide();
$('#form-part-2').fadeIn();
}
});

Retaining textbox text after postback event

I have 3 textBoxes in a page .One of the textBox takes the new Password from the user and according to the password entered by the user , a Label displays Password strength message.But after the message displayed by the Label , the textBox text is cleared.is there a way to retain the text? I have enabled the autopostback for the textbox since i need to use the Comparevalidator for it.
Here is the code snippet-
protected void NewPassEntered(object sender, EventArgs e)
{
if (txtPassword.Text.Length < 4)
{
lblPassStr.Visible = Visible;
lblPassStr.BackColor = System.Drawing.Color.OrangeRed;
lblPassStr.Text = "Password should have more than four characters";
txtPassword.Text = "";
}
else if ((txtPassword.Text.Length > 4) && (txtPassword.Text.Length < 6) && (txtPassword.Text.Contains("#")))
{
lblPassStr.Visible = Visible;
lblPassStr.BackColor = System.Drawing.Color.Green;
lblPassStr.Text = "Password Strength:Medium";
}
else if ((txtPassword.Text.Length > 4) && (txtPassword.Text.Length < 6))
{
lblPassStr.Visible = Visible;
lblPassStr.BackColor = System.Drawing.Color.Yellow;
lblPassStr.Text = "Password Strength:Weak";
}
else if ((txtPassword.Text.Length > 6) && (txtPassword.Text.Contains("#")))
{
lblPassStr.Visible = Visible;
lblPassStr.BackColor = System.Drawing.Color.Blue;
lblPassStr.Text = "Password Strength:Strong";
}
}
}
Is there a way to check multiple special characters efficiently?
The aspx code looks like this-:
<div style="width:400px; height:250px;border-color:GoldenRod ;border-style:solid;border-width:thin;padding:20px 50px 50px 20px; position:relative; margin:100px 100px; margin-left:344px">
<table border="0" align="center" cellpadding="0" cellspacing="0" width="350" >
<tr><td> <br /></td></tr>
<tr>
<td style="width:200px">
<span class="labeltxt"> Old Password: </span>
<br /></td></tr><tr> <td style="width:200px"> <asp:TextBox ID="txtoldpass"
runat="server" CssClass="text" TextMode="Password" Width="300px"
Height="25" ></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="*Enter the old password" ControlToValidate="txtoldpass" Text="*" ForeColor="Red" InitialValue="">
</asp:RequiredFieldValidator><br />
</td>
</tr>
<tr>
<td><br /></td>
</tr>
<tr>
<td style="width:200px">
<span>New Password: </span>
<br /></td></tr><tr>
<td style="width:200px">
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password" CssClass="text"
Width="300px" Height="25"
ontextchanged="NewPassEntered"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Font-Italic="true" ErrorMessage="**Enter the new password!" ControlToValidate="txtPassword" Text="**" ForeColor="Red" InitialValue="">
</asp:RequiredFieldValidator>
<br /></td>
</tr>
<tr>
<td><br />
<asp:Label ID="lblPassStr" runat="server" Text="Label" Visible="False"></asp:Label></td>
</tr>
<tr>
<td style="width:200px">
<span>Confirm Password:</span>
<br /> </td></tr>
<tr>
<td style="width:200px"> <asp:TextBox ID="txtPassword1" runat="server"
TextMode="Password" CssClass="text" Width="300px" Height="25"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="***Enter the new password again!" ControlToValidate="txtPassword1" Text="***" ForeColor="Red" InitialValue="">
</asp:RequiredFieldValidator>
<asp:CompareValidator ID="CompareValidator1" runat="server"
ErrorMessage="Passwords do not Match!" ControlToCompare="txtPassword"
ControlToValidate="txtPassword1"></asp:CompareValidator>
<br /> </td>
</tr>
<tr>
<td><br /><br /></td>
</tr>
<tr>
<td>
<asp:Button runat="server" ID="btnLogin" Text="Save" Height="25px"
Width="76px" CssClass="btn" BackColor="Goldenrod" onclick="btnLogin_Click"></asp:Button><asp:HyperLink ID="HyperLink1" runat="server">Cancel</asp:HyperLink>
</td>
</tr>
</table>
</div>
<asp:ValidationSummary ID="ValidationSummary1" Font-Italic="true" font-size="Small" forecolor="Black" runat="server" />
Don't postback the whole page for just setting a Password strength label. Use Javascript for this. There will be 2 benefits of using javascript here.
1) The page will not be postback (By Postback whole page will be refreshed and just because of a single field whole page postback is not a good practice)
2) No need to maintain the state of textbox as there is no postback.
What about using EnableViewState =false ?
<asp:TextBox ID="txtoldpass" runat="server" EnableViewState ="False" CssClass="text" TextMode="Password"
Width="300px" Height="25" ></asp:TextBox>

What is the error in my Validation in asp.net application?

net application. With this application a user can add a guestconnection for a time. for this i have a button that open a modal dialog who a user can add a guest. the input must be a firstname,lastname,company and the time. i use the validation controls and a ValidationGroup. The Validationcontrols check if I forget a input but if I click on "add" the code doesn't run. I try this with a simple div but the same method:
Here is my aspx code:
<div id="add">
<div id="Div2" class="popupConfirmation" runat="server" style="width:350px; height:290px;">
<div class="bodycontrol">
<table>
<tr>
<td><asp:Label ID="Label3" runat="server" Text="Vorname"></asp:Label></td>
<td><asp:TextBox ID="TextBox1" runat="server" ValidationGroup="valid" ></asp:TextBox></td>
<td><asp:RequiredFieldValidator ID="RequiredFieldValidator1" ValidationGroup="valid" runat="server" ForeColor="red" ErrorMessage="*" ControlToValidate="TextBox1"></asp:RequiredFieldValidator></td>
</tr>
<tr>
<td><asp:Label ID="Label4" runat="server" Text="Nachname"></asp:Label></td>
<td><asp:TextBox ID="TextBox2" runat="server" ValidationGroup="valid"></asp:TextBox></td>
<td><asp:RequiredFieldValidator ID="RequiredFieldValidator2" ValidationGroup="valid" runat="server" ForeColor="red" ErrorMessage="*" ControlToValidate="TextBox2"></asp:RequiredFieldValidator></td>
</tr>
<tr>
<td><asp:Label ID="Label5" runat="server" Text="Firma"></asp:Label></td>
<td><asp:TextBox ID="TextBox3" runat="server" ValidationGroup="valid"></asp:TextBox></td>
<td><asp:RequiredFieldValidator ID="RequiredFieldValidator3" ValidationGroup="valid" runat="server" ForeColor="red" ErrorMessage="*" ControlToValidate="TextBox3"></asp:RequiredFieldValidator></td>
</tr>
</table>
<br />
<table>
<tr>
<td><asp:LinkButton ID="LinkButton1" runat="server" class="GuestButtons" Text="Hinzufügen" ValidationGroup="valid" onclick="btn_GuestListViewAddDialog_YES_Click" ></asp:LinkButton></td>
<td><asp:LinkButton ID="LinkButton2" runat="server" class="GuestButtons" Text="Abbrechen" ValidationGroup="never"></asp:LinkButton></td>
</tr>
</table>
<br />
<table>
<tr>
<td><asp:Label ID="Label10" runat="server" Text="*Bitte alle Felder ausfüllen"></asp:Label></td>
</tr>
</table>
</div>
</div>
</div>
here is my c# code:
protected void btn_GuestListViewAddDialog_YES_Click(object sender, EventArgs e)
{
if (Page.IsValid) //Here i make a breakpoit but it doesn't use this code :(
{
...//here is my code
}
}
this is in my script block if i click on the linkbutton:
WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$lw_content$LinkButton1", "", true, "valid", "", false, true))
If you want to force validation on serverside you need to call Page.Validate() before you check Page.IsValid.
protected void btn_GuestListViewAddDialog_YES_Click(object sender, EventArgs e)
{
Page.Validate();
if (Page.IsValid)
{
The LinkButton must also have a ValidationGroup, the same valid-group if you want to validate this group if the link-button was clicked or a different group if you don't want to trigger validation.
Edit: However, Page.Validate should be redundant since CausesValidation is true by default for a LinkButton and you have specified also a ValidationGroup for it. So i'm at a loss.

Controls does not exist in current context in ASP.Net CreateUserWizard

I am working on a project in Microsoft Visual Studio using an ASP.NET web application with code behind in C#. I added a CreateUserWizard and customized the form in step 1. From the events handler I put a CreatedUser handler into the codebehind to update database tables.
I want to pull the data values for the handler from the form, but the codebehind file can't see them for some reason. Help!
Main Page
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="PageControls" runat="server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="RightBox" runat="server">
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="SiteControl1" runat="server">
</asp:Content>
<asp:Content ID="Content5" ContentPlaceHolderID="SiteControl2" runat="server">
</asp:Content>
<asp:Content ID="Content6" ContentPlaceHolderID="SiteControl3" runat="server">
</asp:Content>
<asp:Content ID="Content7" ContentPlaceHolderID="CPMain" runat="server">
<center>
<asp:CreateUserWizard ID="CreateUserWizard1" runat="server"
CreateUserButtonText="Submit"
RequireEmail="False" OnCreatedUser="CreateUserWizard1_CreatedUser">
<WizardSteps>
<asp:CreateUserWizardStep ID="CreateUserWizardStep1" runat="server">
<ContentTemplate>
<table border="0" style="font-size: 100%">
<tr>
<td align="center" colspan="2" style="font-weight:
bold; color: white; background-color: #5d7b9d">
Register with Acme!
</td>
</tr>
<tr>
<td align="right">
<asp:Label ID="Label1" runat="server"
AssociatedControlID="UserName">
First Name:</asp:Label>
</td>
<td>
<asp:TextBox ID="FName" runat="server">
</asp:TextBox>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator1" runat="server" ControlToValidate="FirstName"
ErrorMessage="First Name is required."
ToolTip="First Name is required." ValidationGroup="CreateUserWizard1">*
</asp:RequiredFieldValidator>
</td>
<tr>
<td align="right">
<asp:Label ID="Label2" runat="server">
Last Name:</asp:Label>
</td>
<td>
<asp:TextBox ID="LName" runat="server">
</asp:TextBox>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator2" runat="server" ControlToValidate="LastName"
ErrorMessage="Last Name is required."
ToolTip="Last Name is required." ValidationGroup="CreateUserWizard1">*
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="right">
<asp:Label ID="UserNameLabel" runat="server"
AssociatedControlID="UserName">
User Name:</asp:Label>
</td>
<td>
<asp:TextBox ID="UserName" runat="server">
</asp:TextBox>
<asp:RequiredFieldValidator
ID="UserNameRequired" runat="server" ControlToValidate="UserName"
ErrorMessage="User Name is required."
ToolTip="User Name is required." ValidationGroup="CreateUserWizard1">*
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="right">
<asp:Label ID="PasswordLabel" runat="server"
AssociatedControlID="Password">
Password:</asp:Label>
</td>
<td>
<asp:TextBox ID="Password" runat="server"
TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator
ID="PasswordRequired" runat="server" ControlToValidate="Password"
ErrorMessage="Password is required."
ToolTip="Password is required." ValidationGroup="CreateUserWizard1">*
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="right">
<asp:Label ID="ConfirmPasswordLabel"
runat="server" AssociatedControlID="ConfirmPassword">
Confirm Password:</asp:Label>
</td>
<td>
<asp:TextBox ID="ConfirmPassword"
runat="server" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator
ID="ConfirmPasswordRequired" runat="server" ControlToValidate="ConfirmPassword"
ErrorMessage="Confirm Password is
required." ToolTip="Confirm Password is required."
ValidationGroup="CreateUserWizard1">*
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="center" colspan="2">
<asp:CompareValidator ID="PasswordCompare"
runat="server" ControlToCompare="Password"
ControlToValidate="ConfirmPassword"
Display="Dynamic" ErrorMessage="The Password and Confirmation Password must match."
ValidationGroup="CreateUserWizard1">
</asp:CompareValidator>
</td>
</tr>
<tr>
<td align="center" colspan="2" style="color: red">
<asp:Literal ID="ErrorMessage" runat="server"
EnableViewState="False"></asp:Literal>
</td>
</tr>
<tr>
<td align="right">
<asp:Label ID="Label3" runat="server"
AssociatedControlID="UserName">
Role:</asp:Label>
</td>
<td>
<asp:DropDownList ID="RoleSelector"
runat="server">
<asp:ListItem
Value="Visitor">Visitor</asp:ListItem>
<asp:ListItem
Value="Employee">Employee</asp:ListItem>
<asp:ListItem Value="PM">Project
Manager</asp:ListItem>
<asp:ListItem Value="DM">Department
Manager</asp:ListItem>
<asp:ListItem Value="Director">IT
Director</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
</table>
</ContentTemplate>
</asp:CreateUserWizardStep>
<asp:CompleteWizardStep ID="CompleteWizardStep1" runat="server">
<ContentTemplate>
</ContentTemplate>
</asp:CompleteWizardStep>
</WizardSteps>
</asp:CreateUserWizard>
</center>
</asp:Content>
CodeBehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Principal;
namespace Acme
{
public partial class Register : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
{
RolesManager.InsertEmployee(FName.Text, LName.Text, RoleSelector.Value,
User.Identity);
}
}
}
I get these errors at compile time:
Error 1 The name 'FName' does not exist in the current context C:\MV_Training\Jan2013\C#Projects\AcmePresentation\AcmePresentation\Register.aspx.cs 20 41 AcmePresentation
Error 2 The name 'LName' does not exist in the current context C:\MV_Training\Jan2013\C#Projects\AcmePresentation\AcmePresentation\Register.aspx.cs 20 53 AcmePresentation
Error 3 The name 'RoleSelector' does not exist in the current context C:\MV_Training\Jan2013\C#Projects\AcmePresentation\AcmePresentation\Register.aspx.cs 20 65 AcmePresentation
and this from the browser:
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS1061: 'ASP.register_aspx' does not contain a definition for 'CreateUserWizard1_CreatedUser' and no extension method 'CreateUserWizard1_CreatedUser' accepting a first argument of type 'ASP.register_aspx' could be found (are you missing a using directive or an assembly reference?)
Source Error:
Line 16: <asp:Content ID="Content7" ContentPlaceHolderID="CPMain" runat="server">
Line 17: <center>
Line 18: <asp:CreateUserWizard ID="CreateUserWizard1" runat="server"
Line 19: CreateUserButtonText="Submit" RequireEmail="False"
Line 20: oncreateduser="CreateUserWizard1_CreatedUser">
Source File: c:\MV_Training\Jan2013\C#Projects\AcmePresentation\AcmePresentation\Register.aspx Line: 18
Thanks,
Bill
You want to cast controls explicitly something like this -
public void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
{
var fNameTextBox = (TextBox)CreateUserWizardStep1
.ContentTemplateContainer.FindControl("FName");
var lNameTextBox = (TextBox)CreateUserWizardStep1
.ContentTemplateContainer.FindControl("LName");
var usernameTextBox = (TextBox)CreateUserWizardStep1
.ContentTemplateContainer.FindControl("UserName");
MembershipUser user = Membership.GetUser(usernameTextBox.Text);
Guid userId = (Guid)user.ProviderUserKey;
}

Categories

Resources