I am working on a contact page and would like some help please on how to display error labels at individual times when the textboxes are empty. I have used 3 textboxes. I am a new student in C# asp.net. I really appreciate your time and help. Thanks!
//if no or incorrect entries are entered panel with red message using a label appears to remind the user of
//if name, email, enquiry is blank error labels show up
if (nameContactUsTextBox.Text == "" && emailContactUsTextBox.Text == "" && enquiryContactUsTextBox.Text == "")
{
nameErrorLabel.Visible = true;
emailErrorLabel.Visible = true;
equiryErrorLabel.Visible = true;
}
if (nameContactUsTextBox.Text != "" && emailContactUsTextBox.Text == "" && enquiryContactUsTextBox.Text == "")
{
emailErrorLabel.Visible = true;
equiryErrorLabel.Visible = true;
}
if (nameContactUsTextBox.Text == "" && emailContactUsTextBox.Text != "" && enquiryContactUsTextBox.Text == "")
{
nameErrorLabel.Visible = true;
equiryErrorLabel.Visible = true;
}
if (nameContactUsTextBox.Text == "" && emailContactUsTextBox.Text == "" && enquiryContactUsTextBox.Text != "")
{
nameErrorLabel.Visible = true;
emailErrorLabel.Visible = true;
}
aspx file
<p>
<table style="width: 100%;">
<tr>
<td class="boring">Name</td>
<td class="auto-style1">
<asp:TextBox ID="nameContactUsTextBox" runat="server" CssClass="boring" ToolTip="Enter Name" Width="441px"></asp:TextBox>
<asp:Label ID="nameErrorLabel" runat="server" CssClass="redalert" Text="*complete name" Visible="False"></asp:Label>
</td>
</tr>
<tr>
<td class="boring">E-Mail</td>
<td>
<asp:TextBox ID="emailContactUsTextBox" runat="server" CssClass="boring" ToolTip="Enter Email" Width="443px"></asp:TextBox>
<asp:Label ID="emailErrorLabel" runat="server" CssClass="redalert" Text="*complete email" Visible="False"></asp:Label>
</td>
</tr>
<tr>
<td class="boring">Enquiry</td>
<td class="auto-style5">
<asp:TextBox ID="enquiryContactUsTextBox" runat="server" CssClass="classic" Height="158px" ToolTip="Enter Enquiry" Width="441px"></asp:TextBox>
<asp:Label ID="equiryErrorLabel" runat="server" CssClass="redalert" Text="*complete enquiry" Visible="False"></asp:Label>
</td>
</tr>
<tr>
<td class="auto-style5"></td>
<td class="auto-style2"></td>
</tr>
<tr>
<td class="smallheader" colspan="2"> </td>
</tr>
<tr>
<td class="auto-style5"> </td>
<td class="auto-style2"> </td>
</tr>
<tr>
<td class="auto-style5" colspan="2">
<asp:Button ID="sendButton" runat="server" CssClass="smallheader" OnClick="sendButton_Click" Text="Send" ToolTip="Sending to NeoMan!" Width="200px" />
<asp:Button ID="homeButton" runat="server" CssClass="smallheader" OnClick="homeButton_Click" Text="Home" ToolTip="Continue Shopping With NeoMan" Width="200px" />
<asp:Button ID="resetButton" runat="server" CssClass="smallheader" OnClick="resetButton_Click" Text="Reset Form" ToolTip="Clear Form" Width="200px" />
</td>
</tr>
<tr>
You could use the TextChangedEvent like so:
protected void nameContactUsTextBox_TextChanged(object sender, EventArgs e)
{
nameErrorLabel.Visible = nameContactUsTextBox.Text == "";
}
And add the textchanged-event for each of the textboxes.
Microsoft already have buil ib validators that you can use to do this sort of task. To make sure that the field is not empty use the Required Field validator see this example on the w3c school website http://www.w3schools.com/aspnet/showaspx.asp?filename=demo_reqfieldvalidator.
For more complex validation use can use the regular expression validator. check the msdn website(http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.regularexpressionvalidator%28v=vs.110%29.aspx) for this it quite straight forward.
you can also investigate the JQuery validator it is quite flexible to do more interesting validation.
That's because you need to hide labels when they're not supposed to be shown, not only hide it. Change ifs to if-elses and add a summary else condition
else
{
nameErrorLabel.Visible = false;
emailErrorLabel.Visible = false;
equiryErrorLabel.Visible = false;
}
You should use the
placeholder
property of the textbox to display the type of value you need entered and examine those answers with jquery either after the boxes lose focus or upon a click of a button. If you need some sample code let me know
Related
I've have one table, in that table within one I've one and within that , I've update panel whose update mode is set to conditional. Within this update panel I've another table. The table contains 3 text boxes as: old password, new password and confirm password. On the textChanged event of the old password I am checking the user entered value with the value in db. But when the function completes its execution all the 3 text boxes looses its values regardless of whether I update the update panel or not. I don't know why it clears text boxes. I want to prevent text boxes from getting cleared. I tried to get the text box text in string variable and again assign it to text boxes (both in text box text changed event and in page load event under isPostBack condition) but its too, not working.
asp code:
.
.
.
<tr>
<td colspan="3">
<div>
<asp:UpdatePanel ID="updPnlChngPwd" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<table style="width:100%">
<tr>
<td>
Old Password
</td>
<td>:</td>
<td>
<asp:TextBox ID="txtOldPwd" runat="server" Height="21px" MaxLength="50" TextMode="Password" Width="60%" ontextchanged="txtOldPwd_TextChanged"
AutoPostBack="True"></asp:TextBox>
</td>
</tr>
<tr>
<td></td>
<td></td>
<td>
<asp:Label ID="lblWrongOldPwd" runat="server" Text="Wrong Old Password" ForeColor="Red" Visible="False"></asp:Label>
</td>
</tr>
<tr>
<td>
Password
</td>
<td>:</td>
<td></td>
</tr>
<tr>
<td></td>
<td>:</td>
<td>
<asp:TextBox ID="txtSuppRePwd" runat="server" Height="21px" MaxLength="50" TextMode="Password" Width="60%"></asp:TextBox>
</td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="btnUpdPwd" runat="server" Text="Change Password" onclick="btnUpdPwd_Click"/></td>
<td>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<td>
</tr>
.
.
.
C# code for tetxt box textChanged event:
protected void txtOldPwd_TextChanged(object sender, EventArgs e)
{
DataTable dtOldPwd = Obj.DBAccess("select Pwd from Customer where Cust_Id = " + Convert.ToInt32(Session["SuppID"]) + " and Supp_Pwd = '" + txtOldPwd.Text + "'");
if (dtOldPwd.Rows.Count == 1)
{
lblWrongOldPwd.Visible = false;
}
else
{
lblWrongOldPwd.Visible = true;
updPnlChngPwd.Update();
}
}
Now I am not able to understand what exactly wrong I am doing, does having update panel inside the table causing problem?
<td>
<asp:TextBox ID="txtSuppRePwd" runat="server" Height="21px" MaxLength="50" TextMode="Password" Width="60%"></asp:TextBox>
</td>
You have TextMode set to password which will not save your textbox value .
However you will get your textbox value as string on textchange event
protected void txtbx_TextChanged(object sender, EventArgs e)
{
string txtValue = txtbx.Text;
ViewState["xyz"]= txtValue;
}
and you have to save this value in ViewState to use it for btnClick event .
OR
You can also set textbox attribute at Page_Load event which is a very bad practice to do like this
protected void Page_Load(object sender, EventArgs e)
{
txtbx.Attributes.Add("value", txtbx.Text);
TextBox with TextMode="Password" will be cleared after postback or partial postback. This is the default behavior of the password textbox so submit all the data at a time and do the validation in your code.
Alternatively, You can store password in in viewstate or session and restore after postback.
Problem: I have an asp.net Textbox that I am putting text into and on text change it should assign its value to a variable, this does not happens.
Question: What is the best method to retrieve the value from the Textbox?
C# Code:
protected void btnSourceConnect_Click(object sender, EventArgs e)
{
if (Util.Connection(SourceString, 0))
{
lblTesting.Text = "Working!";
}
else
{
lblTesting.Text = "It No Work";
}
}
protected void txtSourceServer_TextChanged(object sender, EventArgs e)
{
SourceString.DataSource = txtSourceServer.Text;
}
protected void txtSourceDatabase_TextChanged(object sender, EventArgs e)
{
SourceString.InitialCatalog = txtSourceDatabase.Text;
}
protected void txtSourceUN_TextChanged(object sender, EventArgs e)
{
SourceString.UserID = txtSourceUN.Text;
}
protected void txtSourcePass_TextChanged(object sender, EventArgs e)
{
SourceString.Password = txtSourcePass.Text;
}
Asp.Net Code:
<table style="width: 100%;Border:1px solid Black;">
<tr>
<td class="style1">
Source Server:</td>
<td class="style1">
<asp:TextBox ID="txtSourceServer" runat="server"
ontextchanged="txtSourceServer_TextChanged" AutoPostBack="True"></asp:TextBox>
</td>
<td class="style1">
Source Database:
</td>
<td class="style1">
<asp:TextBox ID="txtSourceDatabase" runat="server"
ontextchanged="txtSourceDatabase_TextChanged" AutoPostBack="True"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style1">
User Name:
</td>
<td class="style1">
<asp:TextBox ID="txtSourceUN" runat="server"
ontextchanged="txtSourceUN_TextChanged" AutoPostBack="True"></asp:TextBox>
</td>
<td class="style1">
Password:
</td>
<td class="style1">
<asp:TextBox ID="txtSourcePass" runat="server"
ontextchanged="txtSourcePass_TextChanged" AutoPostBack="True"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style1">
</td>
<td class="style1">
</td>
<td class="style1">
</td>
<td class="style1">
<asp:Button ID="btnSourceConnect" runat="server" Text="Test Connection"
onclick="btnSourceConnect_Click" />
</td>
</tr>
</table>
What is the best method to retrieve the value from the Textbox?
The best method is like this control I am writing right now, you have a button that make post back, and then you read the value of the text box on code behind - on post back.
Using the AutoPostBack="True" on every TextBox you use involves too many unnecessary post backs to the server, it is better to use a "submit" button and save all your values when the user click on submit.
In you case you have a button, and you only need to remove the auto post back and set your values only when you try to connect as:
protected void btnSourceConnect_Click(object sender, EventArgs e)
{
SourceString.UserID = txtSourceUN.Text;
SourceString.DataSource = txtSourceServer.Text;
SourceString.InitialCatalog = txtSourceDatabase.Text;
SourceString.Password = txtSourcePass.Text;
if (Util.Connection(SourceString, 0))
{
lblTesting.Text = "Working!";
}
else
{
lblTesting.Text = "It No Work";
}
}
AutoPostback = true on a TextBox will cause the page to post back when the text box loses focus, not on every text change.
From the look of your code most of this functionality should be happening on the client side (i.e. with javascript).
I have a following code in aspx page:
<TABLE id="tblGeneratedTo" cellspacing="0" cellpadding="0" width="100%" align="left" border="0" runat="server">
<TR>
<td width="20%" align="left"><FONT face="Verdana" size="2"><strong>To:</strong></FONT> </TD>
<td width="80%">
<asp:textbox id="txtGeneratedTo" runat="server" CssClass="ptinput" MaxLength="10" Width="90px"></asp:textbox>
<A onclick="window.open('../calPopUp.aspx?textbox=txtGeneratedTo','cal','width=230,height=190,left=400,top=200')"
href="javascript:;"> <IMG src="../images/SmallCalendar.gif" border="0"></A> <FONT class="fontbody">
(mm/dd/yyyy)</FONT>
</TD>
</TR>
<tr>
<td colspan="2" align="right">
<asp:RegularExpressionValidator ID="Regularexpressionvalidator4" runat="server" CssClass="fontbody"
Display="Dynamic" ErrorMessage="*Date should be in (mm/dd/yyyy) format."
ValidationExpression="^([\d]{1,2}/[\d]{1,2}/[\d]{4})$"
ControlToValidate="txtGeneratedTo"></asp:RegularExpressionValidator>
<asp:CompareValidator ID="CompareValidator6" runat="server" CssClass="fontbody"
Display="Dynamic" ErrorMessage="'End' date cannot fall before 'Start' date."
ControlToValidate="txtGeneratedTo" Type="Date" Operator="GreaterThanEqual"
ControlToCompare="txtGeneratedFrom"></asp:CompareValidator>
</td>
</tr>
</TABLE>
To:
(mm/dd/yyyy)
Here I have a textbox and two validation controls on it viz. regular expression and compare on actual page when I put some garbage value in textbox I see both the message at a time:
I want to see only one message at a time. Most preferably show comparevalidator message iff regularexpression validator is satisfied or else show only regularexpression validator.
How to achieve this? It will be easy if we can do something for this from MarkUp only rather than codebehind.
For this you have to use CustomValidator. The Validator
<asp:CustomValidator ID="CompareDateValidator" runat="server"
ClientValidationFunction="CompareDateValidatorClient"
ErrorMessage="Some error message" />
The ClientValidationFunction that accompanies this
function CompareDateValidatorClient(sender, args) {
var fromValue = document.getElementById('<%=txtGeneratedFrom.ClientID%>').value;
var toValue = document.getElementById('<%=txtGeneratedTo.ClientID%>').value;
var isValid = false;
if (ValidateDate(fromValue)) {
if (ValidateDate(toValue)) {
if (Date.parse(toValue) > Date.parse(fromValue)) {
isValid = true;
}
else
sender.innerHTML = "'End' date cannot fall before 'Start' date.";
}
else
sender.innerHTML = "To date should be in (mm/dd/yyyy) format.";
}
else
sender.innerHTML = "From date should be in (mm/dd/yyyy) format.";
args.IsValid = isValid;
}
function ValidateDate(str) {
var rm_date = /^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$/;
//triple check for not empty, mm/dd/yyyy format and whether the date is valid
return (str.trim() !== "" && str.match(rm_date) && !isNaN(Date.parse(str)));
}
//remedial javascript. trim function
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s*(\S*(?:\s+\S+)*)\s*$/, "$1");
};
}
// ControlToValidate property supports hooking up single element.
//The below hack hooks both txtGeneratedFrom and txtGeneratedTo to the validator
var validatorObj = document.getElementById("<%= CompareDateValidator.ClientID %>");
ValidatorHookupControlID("<%= txtGeneratedFrom.ClientID %>", validatorObj);
ValidatorHookupControlID("<%= txtGeneratedTo.ClientID %>", validatorObj);
Depending upon the responses from the user when they complete a form, controls may or may not be required. All of these controls have validation attached to them. For instance, if the user hasn't lived at their address for at least 2 years, I need to validate previous address information; if not, I need to skip that validation.
I've tried disabling the validator control with jQuery and although when the validation text is 'greyed out', it still causes validation.
<script src="../../Scripts/jquery-1.6.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#ddlSpouseData').change(
function () {
var selection = $('#<%= ddlAddressData.ClientID%>').get(0).selectedIndex;
if (selection == 1) {
alert(selection);
$('#rfvAddressType').attr('disabled', 'disabled');
$('#rfvBAddress').attr('disabled', 'disabled');
}
});
});
</script>
<table id="MyTable" class="tableModule">
<tr>
<td class="tableDataBorder">
Data is not available and<br /> will be provided later.
</td>
<td class="tableDataBorder">
<asp:DropDownList ID="ddlAddressData" runat="server">
<asp:ListItem>Please Select</asp:ListItem>
<asp:ListItem>Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr class="hideRow">
<td class="tableDataBorder">
Identifying Document
</td>
<td class="tableDataBorder">
<asp:DropDownList ID="ddlAddressType" runat="server">
<asp:ListItem>Please Select</asp:ListItem>
<asp:ListItem>Home</asp:ListItem>
<asp:ListItem>Office</asp:ListItem>
<asp:ListItem>Other</asp:ListItem>
</asp:DropDownList>
<br />
<asp:RequiredFieldValidator ID="rfvAddressType" CssClass="regexError" ControlToValidate="ddlAddressType"
runat="server" ErrorMessage="Please select address type" Display="Dynamic"
InitialValue="Please Select"></asp:RequiredFieldValidator>
</td>
</tr>
<tr class="hideRow">
<td class="tableDataBorder">
Address
</td>
<td>
<asp:TextBox ID="txtAddress" MaxLength="50" runat="server" CssClass="StdTxtBox"></asp:TextBox><br />
<asp:RequiredFieldValidator ID="rfvBAddress" CssClass="regexError" ControlToValidate="txtAddress"
runat="server" ErrorMessage="Please enter your address" Display="Dynamic"></asp:RequiredFieldValidator>
</td>
</tr>
</table>
Instead of your RequiredFieldValidator, use a CustomValidator instead.
So for example you can change your 'rfvAddressType' requiredfieldvalidator as follows:
<asp:CustomValidator runat="server"
id="valAddressType"
controltovalidate="ddlAddressType"
onservervalidate="cusCustom_ServerValidate"
errormessage="Please select address type" />
Then on the server code:
protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
{
if (ddlAddressType.SelectedItem.Value == "1")
e.IsValid = false; // or do any additional validation checks here!
else
e.IsValid = true;
}
More details here:
http://asp.net-tutorials.com/validation/custom-validator/
https://web.archive.org/web/20211020145934/https://www.4guysfromrolla.com/articles/073102-1.aspx
Try disabling or enabling validators on the run to achieve your desired functionality. You can try this code. I haven't tested it.
//Syntax:
ValidatorEnable(ValidatorContronName,Boolean);
//Explanation:ValidatorContronName - This is ClientID of the Validation control.
Boolean - true(Enable) / false(Disable)
//Example:
ValidatorEnable(document.getElementById('<%=rfvAddressType.ClientID%>'), false);
I have a sales simulator written in C#. I did not write this however I am currently modifying it to suit different requirements.
It basically displays a list of products from a database, and has a textbox for each product where you can enter in the quantity sold. The quantity sold is calculated based on it's price in the database.
Now it's all working fine, however there is one SMALL issue. When "Buy" is clicked, it returns me back to the list of products which IS correct, however the quantity I have entered for the previous product remains.
I would like to know how to restore the text boxes to their default value when the after the data is submitted to the database.
I always thought the way to do this would be in the .cs code behind file
txtQuantity.Text = "";
However, for some odd reason, txtQuantity will not show up.
Can anyone think of anything I am doing wrong? Here is a snippet of code from the aspx file.
<form id="form1" runat="server">
Date:
<asp:TextBox ID="txtDate" runat="server" />
Retailer:
<asp:DropDownList ID="dlStore" runat="server"
onselectedindexchanged="dlStore_SelectedIndexChanged" />
<asp:ListView ID="lbProducts" runat="server">
<LayoutTemplate>
<layouttemplate>
<table border="1" cellpadding="1" style="width:800px">
<tr style="background-color:#E5E5FE">
<th>ID</th>
<th>ProductCode</th>
<th>Product Title</th>
<th>RRP $</th>
<th>Quantity</th>
<th>Sale Price $</th>
</tr>
<tr id="itemPlaceholder" runat="server"></tr>
</table>
</layouttemplate>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td style="width: 50px;">
<%#Eval("ProductID") %>
</td>
<td>
<%#Eval("ProductCode") %>
</td>
<td>
<%#Eval("ProductTitle") %>
</td>
<td>
<%#Eval("USListPrice") %>
</td>
<td style="width: 50px;">
<asp:TextBox ID="txtQuantity" runat="server" Text="0" />
</td>
<td style="width: 50px;">
<asp:TextBox ID="txtSalePrice" runat="server" Text="0.00" />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
<asp:Button ID="btnBuy" Text="Buy These Items" runat="server" OnClick="btnBuy_Click" />
<asp:Button ID="btnClear" Text="Clear Existing Sales" runat="server"
onclick="btnClear_Click" />
</form>
There's a lot going on in the code behind file and I wouldn't expect anyone to go through it, but how I collect the data from txtQuantity is done with the following line of code:
Int32 quantity = Int32.Parse(((TextBox)item.FindControl("txtQuantity")).Text);
So what I want to be able to do is set this textbox either to be empty, or back to zero.
Any help is appreciated, thanks.
Because that txtQuantity control is within a ListView, there could be any number of instances of that control generated. So you can't access all of them through a single variable.
You will need to look through all controls within that ListView (and several levels deep) to find all your txtQuantity controls.
The same of course for the txtSalePrice control.
EDIT
You could find those textboxes with code like (untested)
public IEnumerable<TextBox> FindTextBoxes(Control parent)
{
if (parent == null) yield break;
foreach (Control child in parent.Controls)
{
TextBox tb = child as TextBox;
if (tb != null)
yield return tb; // found one!
else
foreach(TextBox tb in FindTextBoxes(child))
yield return tb; // found it deeper
}
}
and call it like:
foreach(TextBox tb in FindTextBoxes(lbProducts)
{
if (tb.Name == "txtQuantity")
{
// found a quantity
}
else if (tb.Name == "txtSalePrice")
{
// found the salesprice
}
}