Reputation: 1
When user submits, project goes thru validation. Really the issues I was having was with the If
statements. Did I do them right / is there any way to do that part better?
protected void btnSubmit_Click(object sender, EventArgs e)
{
// Check Input for Validation
//Mass Validation ensure everything has a vaule
if (txtFirstName.Text == "" && txtLastName.Text == "" && txtPayRate.Text == ""
&& txtStartDate.Text == "" && txtEndDate.Text == "")
{
txtFirstName.BackColor = System.Drawing.Color.Yellow;
txtLastName.BackColor = System.Drawing.Color.Yellow;
txtPayRate.BackColor = System.Drawing.Color.Yellow;
txtStartDate.BackColor = System.Drawing.Color.Yellow;
txtEndDate.BackColor = System.Drawing.Color.Yellow;
return;
}
if (txtFirstName.Text != "")
{
txtFirstName.BackColor = System.Drawing.Color.White;
}
else
{
txtFirstName.BackColor = System.Drawing.Color.Yellow;
return;
}
if (txtLastName.Text != "")
{
txtLastName.BackColor = System.Drawing.Color.White;
}
else
{
txtLastName.BackColor = System.Drawing.Color.Yellow;
return;
}
if (txtPayRate.Text != "")
{
txtPayRate.BackColor = System.Drawing.Color.White;
}
else
{
txtPayRate.BackColor = System.Drawing.Color.Yellow;
return;
}
Session["txtFirstName"] = txtFirstName.Text;
Session["txtLastName"] = txtLastName.Text;
Session["txtPayRate"] = txtPayRate.Text;
Session["txtStartDate"] = txtStartDate.Text;
Session["txtEndDate"] = txtEndDate.Text;
Response.Redirect("frmPersonnelVerified.aspx");
}
Upvotes: 0
Views: 83
Reputation: 696
If this is ASP.NET WebForms, which your code implies, you should be using Web Forms Validation.
Upvotes: 0
Reputation: 125630
protected void btnSubmit_Click(object sender, EventArgs e)
{
var textBoxes = new[] { txtFirstName, txtLastName, txtPayRate, txtStartDate, txtEndDate };
var isValid = true;
foreach (var textBox in textBoxes)
{
if (textBox.Text == "")
{
isValid = false;
textBox.BackColor = System.Drawing.Color.Yellow;
}
else
{
textBox.BackColor = System.Drawing.Color.White;
}
}
if (!isValid)
return;
Session["txtFirstName"] = txtFirstName.Text;
Session["txtLastName"] = txtLastName.Text;
Session["txtPayRate"] = txtPayRate.Text;
Session["txtStartDate"] = txtStartDate.Text;
Session["txtEndDate"] = txtEndDate.Text;
Response.Redirect("frmPersonnelVerified.aspx");
}
But, looks like this is ASP.NET site, so you should probably use RequiredFieldValidator
instead.
Upvotes: 1
Reputation: 19496
You could do something like this instead:
TextBox[] boxes = new[] { txtFirstName, txtLastName, txtPayRate,
txtStartDate, txtEndDate };
IEnumerable<TextBox> unfilledBoxes = boxes.Where(b => b.Text == "");
foreach (TextBox box in unfilledBoxes)
{
box.BackColor = System.Drawing.Color.Yellow;
}
if (!unfilledBoxes.Any())
{
Session["txtFirstName"] = txtFirstName.Text;
Session["txtLastName"] = txtLastName.Text;
Session["txtPayRate"] = txtPayRate.Text;
Session["txtStartDate"] = txtStartDate.Text;
Session["txtEndDate"] = txtEndDate.Text;
Response.Redirect("frmPersonnelVerified.aspx");
}
Upvotes: 0