Why is server validation not working in my code? - c#

Below is the code of my simple page's submit button click. I am submitting an empty form but no server validation error messages are showing. What's wrong with my code? When I click on submit, the page just turns blank and nothing happens. I am also unable to attach the debugger.
When I am building my website project, it is not showing any compilation error either. I don't know what I am doing wrong.
protected void btnSubmit_Click(object sender, EventArgs e)
{
// Need to Validate All Required Fields before redirecting to frmPersonalVerified.aspx
bool blnFormIsValid = true;
DateTime dtEndDate;
DateTime dtStartDate;
// Get Date because we have a value.
dtEndDate = DateTime.Parse(txtEndDate.Text);
// Get Date because we have a value.
dtStartDate = DateTime.Parse(txtStartDate.Text);
if (txtFirstName.Text.Trim() == "")
{
txtFirstName.BackColor = System.Drawing.Color.Yellow;
lblError.Text = "Please enter first name.";
blnFormIsValid = false;
}
else
{
lblError.Text = "";
txtFirstName.BackColor = System.Drawing.Color.White;
blnFormIsValid = true;
}
if (txtLastName.Text.Trim() == "")
{
txtLastName.BackColor = System.Drawing.Color.Yellow;
lblError.Text = "Please enter last name.";
blnFormIsValid = false;
}
else
{
lblError.Text = "";
txtLastName.BackColor = System.Drawing.Color.White;
blnFormIsValid = true;
}
if (txtPayRate.Text.Trim() == "")
{
txtPayRate.BackColor = System.Drawing.Color.Yellow;
lblError.Text = "Please enter pay rate.";
blnFormIsValid = false;
}
else
{
lblError.Text = "";
txtPayRate.BackColor = System.Drawing.Color.White;
blnFormIsValid = true;
}
if (txtStartDate.Text.Trim() == "")
{
txtStartDate.BackColor = System.Drawing.Color.Yellow;
lblError.Text = "Please enter start date.";
blnFormIsValid = false;
}
else
{
lblError.Text = "";
txtStartDate.BackColor = System.Drawing.Color.White;
blnFormIsValid = true;
}
if (txtEndDate.Text.Trim() == "")
{
txtEndDate.BackColor = System.Drawing.Color.Yellow;
lblError.Text = "Please enter end date.";
blnFormIsValid = false;
}
else
{
lblError.Text = "";
txtEndDate.BackColor = System.Drawing.Color.White;
blnFormIsValid = true;
}
// Compare Dates
if (DateTime.Compare(dtStartDate, dtEndDate) >= 0)
{
txtStartDate.BackColor = System.Drawing.Color.Yellow;
txtEndDate.BackColor = System.Drawing.Color.Yellow;
lblError.Text = "Please make sure that start date is less than end date.";
blnFormIsValid = false;
}
else
{
lblError.Text = "";
txtStartDate.BackColor = System.Drawing.Color.White;
txtEndDate.BackColor = System.Drawing.Color.White;
blnFormIsValid = true;
}
if (blnFormIsValid == true)
{
//Assign a value to the session variable.
Session["FirstName"] = txtFirstName.Text;
Session["LastName"] = txtLastName.Text;
Session["PayRate"] = txtPayRate.Text;
Session["StartDate"] = txtStartDate.Text;
Session["EndDate"] = txtEndDate.Text;
// Sends A Request from the Browser to the server.
Response.Redirect("frmPersonalVerified.aspx");
}
}
Update
I just used .Equals("")... it's not working. Still blank page is showing up

Ignoring the fact that the correct way is to use ASP.NET's built-in validation tools, the problem is that your program's logic is broken.
You're using blnFormIsValid to store the validity of the form, however its value is meaningless because you're assigning it without paying attention to previous state.
If I submit your page's form with these values...
txtFirstName = "" // this is invalid
txtLastName = "foo" // this is valid
...then it will correctly fail the first validation and blnFormIsValid will be false, however your next check ignores the state of blnFormIsValid and sets it to true simply because txtLastName's value is valid.
This issue stems not from our lack of understanding or knowledge of ASP.NET, but basic programming and logic. A simple step-through or dry-run of your code would have revealed this.
Below are my list of recommendations:
Use ASP.NET Validation controls, like so:
<input type="text" id="firstName" runat="server" />
<asp:RequiredValidator runat="server" controlToValidate="firstName" />
void Page_Load() {
if( Page.IsPostBack) {
Page.Validate();
if( Page.IsValid ) {
// that's all you have to do
}
}
Don't use Hungarian notation
This is when you prefix an identifier with a tag that identifies its type, e.g. "blnFormIsValid" or "txtFirstName". Just use "formIsValid" or "firstName". Hungarian notation is only of use in environments where typing information is not provided by the editor.
Don't use foo == true
... because the operation will evaluate to the same value as foo. In your case you should have if( formIsValid ) instead of if( formIsValid == true ). Avoiding unnecessary use of the == operator can help avoid cases where you accidentally use the = assignment operator instead of the == equality operator (and make your code more readable).

Related

How do i get an information label to appear as i type and disappear when i delete the text

I have a couple of text boxes that i have initially hidden and what I want to do is as the users type I would like the next text box along with the label that goes with it to appear to notify of the next question.
At the same time if they change their mind and delete their response to the first question the next text box and label will disappear once the text has been deleted.
Here is my current code:
private void CreditScoreBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsControl(e.KeyChar) || char.IsDigit(e.KeyChar))
e.Handled = false;
else
e.Handled = true;
if(CreditScoreBox.Text == "")
{
MakeBox.Visible = false;
MakeLabel.Visible = false;
ModelBox.Visible = false;
ModelLabel.Visible = false;
CreditLevelLabel.Visible = false;
}
else
{
MakeBox.Visible = true;
MakeBox.Enabled = true;
MakeLabel.Visible = true;
CreditLevelLabel.Visible = true;
}
I have tried using the TextChanged event with the same result.
I created a Form, with 2 textbox and 1 label. If text exist in textbox1 then label1 and textbox2 become available:
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
textBox2.Enabled = false;
textBox2.Visible = false;
label1.Visible = false;
}
else
{
textBox2.Enabled = true;
textBox2.Visible = true;
label1.Visible = true;
}
}

Error: "Input string was not in a correct format" on false statement

My code is working fine if the statement (numtickets > tickav) is true (if tickets available is greater than tickets ordered) But if other wise, it throws in this error "FormatException was unhandled by user code, Input string was not in a correct format" on int numTick = Convert.ToInt32(txtNumberOfTickets.Text);
I do know that somehow I can use tryparse, i need help putting it in the code.
Any help would be appreciated, thank you
namespace TicketsApp
{
public partial class TicketOrder : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["description"] != null && Session["EventID"] != null && Session["numtickets"] != null && Session["ticketcost"] != null
&& Session["State"] != null && Session["Section"] != null && Session["Row"] != null && Session["date"] != null)
{
if (!IsPostBack)
{
try
{
txtEventDescription.Text = Session["description"].ToString();
txtEventID.Text = Session["EventID"].ToString();
txtTicketsAvailable.Text = Session["numtickets"].ToString();
txtTicketCost.Text = Session["ticketcost"].ToString();
txtState.Text = Session["State"].ToString();
txtSectionNumber.Text = Session["Section"].ToString();
txtRowNumber.Text = Session["Row"].ToString();
txtNumberOfTickets.Focus();
lblOutput.Visible = false;
}
catch
{
lblError.Text = "Please Search for Tickets First!";
lblError.Visible = true;
btnOrderTickets.Visible = false;
Response.Redirect("TicketSearch.aspx");
return;
}
}
}
}
protected void btnOrderTickets_Click(object sender, EventArgs e)
{
TicketsDataAccessDataContext NewOrder = new TicketsDataAccessDataContext();
int numTick = Convert.ToInt32(txtNumberOfTickets.Text);
string s = txtTotalCost.Text.Substring(1);
int totc = Convert.ToInt32(s);
int id = Convert.ToInt32(txtEventID.Text);
DateTime dt = Convert.ToDateTime(Session["date"]);
int returnedValue = NewOrder.PlaceOrderFull(id, txtEventDescription.Text, dt, Session["State"].ToString(), Session["section"].ToString(), Session["Row"].ToString(), numTick, totc, "vfateev");
if (returnedValue != 0)
{
lblOutput.Text = "Error has occured. Please try again";
lblOutput.Visible = true;
btnOrderTickets.Visible = false;
}
else
{
lblOutput.Visible = true;
lblOutput.Text = "Thank you";
btnOrderTickets.Visible = false;
}
}
protected void txtNumberOfTickets_TextChanged1(object sender, EventArgs e)
{
int cos = Convert.ToInt32(txtTicketCost.Text);
int numtickets = Convert.ToInt32(txtNumberOfTickets.Text);
int tickav = Convert.ToInt32(txtTicketsAvailable.Text);
if (numtickets > tickav)
{
lblError.Text = "Please Enter a valid ticket quantity";
lblError.Visible = true;
lblOutput.Text = "";
txtNumberOfTickets.Text = "";
}
else
{
int cost = cos * numtickets + 5;
txtTotalCost.Text = "$" + cost.ToString();
lblOutput.Visible = false;
lblFee.Text = "There is a $5 shipping fee";
lblFee.Visible = true;
lblError.Text = "";}
}
}
}
You can use int.TryParse which returns a boolean and does not throw an exception.
int numTick = 0;
bool result = int.TryParse(txtNumberOfTickets.Text, out numTick );
You can also do some client side validation to ensure that the field is filled in and contains a number.
Here is one of your methods rewritten using Int32.TryParse. I assumed you're doing txtTotalCost.Substring(1) to trim off the currency symbol. There are probably safe ways to do this, I'm just going to trim "$" for this example.
protected void btnOrderTickets_Click(object sender, EventArgs e)
{
int numberOfTickets, ticketCost, eventId;
if(Int32.TryParse(txtNumberOfTickets.Text, out numberOfTickets) &&
Int32.TryParse(txtTotalCost.Text.TrimStart('$'), out ticketCost) &&
Int32.TryParse(txtEventID.Text, out eventId))
{
DateTime dt = Convert.ToDateTime(Session["date"]);
TicketsDataAccessDataContext NewOrder = new TicketsDataAccessDataContext();
int returnedValue = NewOrder.PlaceOrderFull(eventId, txtEventDescription.Text, dt, Session["State"].ToString(), Session["section"].ToString(), Session["Row"].ToString(), numberOfTickets, ticketCost, "vfateev");
if (returnedValue != 0)
{
lblOutput.Text = "Error has occured. Please try again";
lblOutput.Visible = true;
btnOrderTickets.Visible = false;
}
else
{
lblOutput.Visible = true;
lblOutput.Text = "Thank you";
btnOrderTickets.Visible = false;
}
}
else
{
lblOutput.Visible = true;
lblOutput.Text = "Some validation error message here...";
}
}
You will need to make similar modifications to txtNumberOfTickets_TextChanged1 to ensure the user has entered valid text.
simply use something like
To use IsNumeric in C#, add a reference to Microsoft.VisualBasic.dll then
if (Information.IsNumeric(value))
{
DoSomthing();
}
else
{
DoSomethingElse();
}
UPDATE
OPEN VISUAL STUDIO ==> YOUR PROJECT
Click on solution and add reference, choose Microsoft.VisualBasic.dll confrim the new reference will be add to your references into the project.
Go at the top of your page and declare the import statemnet for Microsoft.VisualBasic.dll alias
using Microsoft.VisualBasic.dll;
then where you need to check the value of your textbox
if (Information.IsNumeric(yourtextbox.text.trim()))
{
//case true alias your value is numeric
//do what you need here like assing value to a var or any
//else
}
else
{
//put your logic here in case result is false and value
//is not numeric
}

Show 'saved' label for 2 seconds then hide in c# asp.net

What is the best way to show a label (containing text = saved successfully) after saving data to only be visible (visible = true) and then disappear (become visible = false) after say 2 seconds? I have seen people use timers before but cant get them to work.
if (saved == true)
{
//data saved - show label and then make visible = false
lblsuccess.Visible = true;
lblsuccess.Text = "Visit saved";
}
System.Timers.Timer timer1;
timer1 = new System.Timers.Timer(2000);
timer1.Enabled=false;
timer1.Elapsed += new ElapsedEventHandler(timer1_Elapsed);
void timer1_Elapsed(object sender, ElapsedEventArgs e)
{
lblsuccess.Visible = false;
timer1.Enabled=false;
}
if (saved == true)
{
//data saved - show label and then make visible = false
timer1.Enabled=true;
lblsuccess.Visible = true;
lblsuccess.Text = "Visit saved";
}
Use This one line code in CS
Set by default label Visibility= False;
ScriptManager.RegisterClientScriptBlock (this.Page, typeof (Page ), "script" , "window.setTimeout(function() { document.getElementById('" + lblSubMsg.ClientID + "').style.display = 'none' },2000);", true);
Found this and it did the trick for me! Thanks for your answers above though
if (saved == true)
{
lblsuccess.Visible = true;
lblsuccess.Text = "Visit saved";
ClientScript.RegisterStartupScript(this.GetType(), "HideLabel", "<script type=\"text/javascript\">setTimeout(\"document.getElementById('" + lblsuccess.ClientID + "').style.display='none'\",2000)</script>");
}
Try this :
if (saved == true)
{
//data saved - show label and then make visible = false
lblsuccess.Visible = true;
lblsuccess.Text = "Visit saved";
System.Threading.Thread.Sleep(2000);
lblsuccess.Visible= false;
}
you need to do it by java-script jquery delay function as follows
Note that the delay is an integer indicating the number of milliseconds to delay execution of the next item in the queue.
In doucment.ready function of jquery you can write
$("#lblsuccess").delay(3200).fadeOut(300);
or you want to use client id then
$("#<%=lblsuccess.ClientID %>")..delay(3200).fadeOut(300);

Pass variables using Session throwing an exception

I have a form for clients to fill out, so I decided to make it an digital form. I have three pages subscriber_details, Package_Selection and Bank_Details. When the user has filled in all fields in the first and clicks next the page progresses onto the next till all three has been filled, when all three is filled they direct to a final page where all their details are presented to them for one last time, so that they can make sure its correct... on my subscriber_details.aspx I have the following code to store their details into sessions
protected void btnNext_Click(object sender, EventArgs e)
{
Session["FullName"] = txtFullName.Text;
if (txtCompanyName.Text == String.Empty)
Session["CompanyName"] = "N/A";
else
Session["CompanyName"] = txtCompanyName.Text;
if (txtVAT.Text == String.Empty)
Session["VAT"] = "N/A";
else
Session["VAT"] = txtVAT.Text;
Session["ContactNumber"] = txtContactNumber.Text;
if (txtFax.Text == String.Empty)
Session["Fax"] = "N/A";
else
Session["Fax"] = txtFax.Text;
if (txtDistrict.Text == String.Empty)
Session["District"] = "N/A";
else
Session["District"] = txtDistrict.Text;
Session["City"] = txtCity.Text;
Session["Street"] = txtStreet.Text;
Session["Code"] = txtPostal.Text;
if (txtTrading.Text == String.Empty)
Session["Trading"] = "N/A";
else
Session["Trading"] = txtTrading.Text;
Session["ID"] = txtID.Text;
Session["ContactPerson"] = txtContactPerson.Text;
if (txtEmail.Text == String.Empty)
Session["Email"] = "N/A";
else
Session["Email"] = txtEmail.Text;
}
then on my final.aspx I have the following code to use the sessions and replace the text in labels
protected void Page_Load(object sender, EventArgs e)
{
lblFullName.Text = Session["FullName"].ToString();
lblCompanyName.Text = Session["CompanyName"].ToString();
lblVat.Text = Session["VAT"].ToString();
lblContactNumber.Text = Session["ContactNumber"].ToString();
lblFax.Text = Session["Fax"].ToString();
lblDistrict.Text = Session["District"].ToString();
lblStreet.Text = Session["Street"].ToString();
lblCity.Text = Session["City"].ToString();
lblCode.Text = Session["Code"].ToString();
lblTrading.Text = Session["Trading"].ToString();
lblID.Text = Session["ID"].ToString();
lblContactPerson.Text = Session["ContactPerson"].ToString();
lblMail.Text = Session["Email"].ToString();
}
for some reason I get an "Object reference error", is it because my final.aspx page isn't my next page, because I have to pass through my package.aspx and bank_details.aspx first?
I have required field validators on the sessions that doesn't have an if statement, so the text wont be empty
You are not setting all of the Session variables. For example, you have not set Session["Email"] so the call to lblMail.Text = Session["Email"].ToString(); will throw the exception.
You should populate all Session variables you want to use and also check they are not null before doing .ToString(). This should catch it more gracefully.

try catch validation empty text box

Hey so I have the following code which should throw up the errors if the text boxes are empty but it doesn't it just carries on with what it would do were they not and adds an item with 0 or whatever to the list instead, is there a problem with my code?
private void BtnAdd_Click(object sender, EventArgs e)
{
try
{
theVisit.name = txtName.Text;
theVisit.address = txtAddress.Text;
theVisit.arrival = DateTime.Parse(txtArrival.Text);
//Update theVisit object to reflect any changes made by the user
this.Hide();
//Hide the form
}
catch (Exception)
{
if (txtName.Text == "")
MessageBox.Show("please enter a customer name");
if(txtAddress.Text == "")
MessageBox.Show("Please enter a customer address");
if(txtArrival.Text == "")
MessageBox.Show("Please enter an arrival time");
}
NEW
if (txtName.Text == "" || txtAddress.Text == "" || txtArrival.Text == "")
MessageBox.Show(" Please enter a value into all boxes");
else
theVisit.name = txtName.Text;
theVisit.address = txtAddress.Text;
theVisit.arrival = DateTime.Parse(txtArrival.Text);
//Update theVisit object to reflect any changes made by the user
The try-catch-statement is used to catch and handle exceptions. An exception can be thrown, if an index is out of bounds, if members of a variable set to null are accessed, and in many other situations. A TextBox being empty is not an error by itself and does not throw an exception.
I suggest you to use a completely different approach. Add an ErrorProvider to your form. You find it in the toolbox in the section "Components". Now you can add the following code to your form:
private HashSet<Control> errorControls = new HashSet<Control>();
private void ValidateTextBox(object sender, EventArgs e)
{
var textBox = sender as TextBox;
if (textBox.Text == "") {
errorProvider1.SetError(textBox, (string)textBox.Tag);
errorControls.Add(textBox);
} else {
errorProvider1.SetError(textBox, null);
errorControls.Remove(textBox);
}
btnAdd.Enabled = errorControls.Count == 0;
}
private void Form1_Load(object sender, EventArgs e)
{
txtName.Tag = "Please enter a customer name";
txtAddress.Tag = "Please enter a customer address";
errorProvider1.BlinkStyle = ErrorBlinkStyle.NeverBlink;
ValidateTextBox(txtName, EventArgs.Empty);
ValidateTextBox(txtAddress, EventArgs.Empty);
}
Select the ValidateTextBox method as error handler for the TextChanged event of all your textboxes. Insert the desired message in the Tag property of the textboxes. Set the BlinkStyle property of the ErrorProvider to ErrorBlinkStyle.NeverBlink. You can do these settings in code or in the form designer.
Now a red error symbol will appear next to empty textboxes. If you hoover the mouse over them, a tooltip with the error message will appear.
UPDATE
I updated the code above to automatically disable or enable the "Add"-button. Therefore I added a HashSet that contains all the controls currently being in an error state. If the set is empty the button is enabled, otherwise disabled.
You should always be avoiding try catch where possible, because of performance hits see example below:
//set name
if(string.IsNullOrEmpty(txtName.Text)) MessageBox.Show("please enter a customer name");
else theVisit.name = txtName.Text;
//set address
if(string.IsNullOrEmpty(txtAddress.Text)) MessageBox.Show("please enter a customer address");
else theVisit.address = txtAddress.Text;
//set arrival time
if(string.IsNullOrEmpty(txtArrival.Text)) MessageBox.Show("please enter an arrival time");
else {
DateTime dt = default(DateTime);
bool successParse = DateTime.TryParse(txtArrival.Text, out dt);
if(!successParse) MessageBox.Show("please enter a valid arrival time");
else theVisit.arrival = dt;
}

Categories

Resources