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;
}
Related
What i want to do is:
When the user start typing anything in the textBox2 first make it empty and then start showing what the user is typing.
Then if the user deleting what he was typing then show the original text again.
Now what it does is that i need to delete on my own the text inside but then when i try to type anything i see the original text again since it's empty.
private void textBox2_TextChanged(object sender, EventArgs e)
{
if (textBox2.Text != "" || textBox2.Text == "Enter Email Account")
{
textBox2.Text = "Enter Email Account";
button2.Enabled = false;
}
else
{
button2.Enabled = true;
}
}
You should be using a Watermark. But in case you wish to do it as you started, you set the default value in properties.
You need first of all to create your event handlers during the Enter and Leave event;
private void Form1_Load()
{
textBox1.Text = "Enter Email Account";
textBox1.GotFocus += new EventHandler(textBox1_GotFocus);
textBox1.LostFocus += new EventHandler(textBox1_Leave);
}
Then on Enter, the watermark text should be deleted;
protected void textBox1_GotFocus(object sender, EventArgs e)
{
if (textBox1.Text == "Enter Email Account")
{
textBox1.Text = "";
}
}
Then you re-check on Leave event;
protected void textBox1_Leave(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
textBox1.Text = "Enter Email Account";
}
}
//code for confirm password text box:
private void txtRegPassConfirm_TextChanged_1(object sender, EventArgs e)
{
if (txtRegPassConfirm.Text != txtRegPass.Text)
{
MessageBox.Show("Passwords do not match");
txtRegPassConfirm.Clear();
}
else
{
MessageBox.Show("textbox can not be empty");
}
}
//code for text box Password:
private void txtRegPass_TextChanged(object sender, EventArgs e)
{
if (txtRegPass.Text.Length < 8)
{
MessageBox.Show("Password must be at least 8 characters long");
txtRegPassConfirm.Clear();
}
// code for text box Email:
private void txtRegEmail_TextChanged_1(object sender, EventArgs e)
{
string c = ConfigurationManager.ConnectionStrings["Constr"].ConnectionString;
SqlConnection con = new SqlConnection(c);
con.Open();
SqlCommand cmd = new SqlCommand("EmailReg", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Email", this.txtRegEmail.Text);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows == true)
{
MessageBox.Show("Email = " + dr[4].ToString() + "is Already exist");
txtRegEmail.Clear();
break;
}
Regex r = new Regex("^[a-zA-Z0-9){1,20}#[a-zA-Z0-9){1,20}.[a-zA-Z]{2,3}$");
if (!r.IsMatch(txtRegEmail.Text))
{
txtRegEmail.Clear();
MessageBox.Show("incorrect formate");
}
}
}
//code for button Registration:
private void btnRegistration_Click_1(object sender, EventArgs e)
{
string c = ConfigurationManager.ConnectionStrings["Constr"].ConnectionString;
SqlConnection con = new SqlConnection(c);
con.Open();
SqlCommand cmd = new SqlCommand("RegistrationForm", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#UserName", txtRegUserN.Text);
cmd.Parameters.AddWithValue("#Password", txtRegPass.Text);
cmd.Parameters.AddWithValue("#Confirm", txtRegPassConfirm.Text);
cmd.Parameters.AddWithValue("#Email", txtRegEmail.Text);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows == true)
{
MessageBox.Show("Data Inserted Succesfully");
}
}
if (dr.HasRows == false)
{
MessageBox.Show("Access Denied, enter the correct fields");
}
else
{
MessageBox.Show("Enter correct info");
}
}
When I execute the application and enter the password in a confirm text box, it shows me the message box on entering the first character 'Password don't match'. As well as shows me message in the Password text box 'Password must be at least 8 characters long'. And as same as in the Email text box and I want to apply the Regex but not working. I moved my code in the email section but, it shows me the 'Email is invalid' regex message box. Now, tell me what I can do get the message box when I enter the mismatch words not on entering the first character.
Main Problem:
You are checking your validation rules in TextChanged event of your text boxes. Some options that may help you to perform validation is listed here:
Option1: validate in Click Event of Button
You can check for validations in Click event of your register button some thing like this:
private void registerButton_Click(object sender, EventArgs e)
{
//Check for password length
if (txtRegPass.Text.Length < 8)
{
MessageBox.Show("Password must be at least 8 characters long");
txtRegPass.Focus();
return;
}
//Check for other validations
//...
// don't forget to return; if the state is not valid
//If the code execution reaches here, it means all validation have been passed
//So you can save data here.
}
Option 2: Use Validating Event and ErrorProvider
As a better solution, you can use an ErrorProvider. Put an error provider in form and handle Validatin event of your TextBoxes and set error for that control.
Then in Click event of your register button you can check if there is any validation error or not.
and here a screenshot:
private void ValidationTest_Load(object sender, EventArgs e)
{
this.AutoValidate = System.Windows.Forms.AutoValidate.EnableAllowFocusChange;
}
private void passwordTextBox_Validating(object sender, CancelEventArgs e)
{
if (this.passwordTextBox.TextLength < 8)
{
this.errorProvider1.SetError(this.passwordTextBox, "Password must be at least 8 character");
e.Cancel = true;
}
else
{
this.errorProvider1.SetError(this.passwordTextBox, "");
}
}
private void confirmTextBox_Validating(object sender, CancelEventArgs e)
{
if (this.confirmTextBox.Text != this.passwordTextBox.Text)
{
this.errorProvider1.SetError(this.confirmTextBox, "Password and Confirm must be the same");
e.Cancel = true;
}
else
{
this.errorProvider1.SetError(this.confirmTextBox, "");
}
}
private void registerButton_Click(object sender, EventArgs e)
{
if (this.ValidateChildren())
{
//Do registration here
}
else
{
var listOfErrors = this.errorProvider1.ContainerControl.Controls
.Cast<Control>()
.Select(c => this.errorProvider1.GetError(c))
.Where(s => !string.IsNullOrEmpty(s))
.ToList();
MessageBox.Show("please correct validation errors:\n - " +
string.Join("\n - ", listOfErrors.ToArray()),
"Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Because you are using TextChanged event and it raises every time you change the Text. You should check this on click of your button Register.
Not only this one, your all validations should be checked on the button click.
For the help of user, you can use a Label to show the the message while user is typing something, rather showing a MessageBox. That will be a smooth experience for user.
Here is your solution
private void btnRegistration_Click_1(object sender, EventArgs e)
{
if (txtRegPassConfirm.Text != txtRegPass.Text)
{
MessageBox.Show("Passwords do not match");
txtRegPassConfirm.Clear();
return;
}
else
{
if (txtRegPass.Text.Length < 8)
{
MessageBox.Show("Password must be at least 8 characters long");
txtRegPassConfirm.Clear();
return;
}
}
//put your next code as it is which you wrote in this click event
}
Thanks
The problem is you put your validation code in txtRegPassConfirm_TextChanged_1 function. As the name of the function said, that function will be triggered whenever the text in txtRegPassConfirm textbox changed. That's why you get the MessageBox when you first type.
To solve your problem, put your validation code in the Click event of Register button instead of TextChanged event of each textbox.
Another better solution is: use Error Provider Control to show your error instead of using MessageBox. To know more about it, take a look at MSDN.
The validation can also be done while moving to the next text box(Validation of previous text box input) by pressing tab or by mouse click. This can be done in the textbox events Leave or Enter.
private void textBox1_Leave(object sender, EventArgs e) // This event is triggered while leaving the textbox1
{
if ("a" != textBox1.Text)
{
MessageBox.Show("Invalid");
}
}
private void textBox2_Enter(object sender, EventArgs e)// This event is triggered while entering the textbox2
{
if ("a" != textBox1.Text) //Content of textbox1 is validated
{
MessageBox.Show("Invalid");
}
}
Hi Guys this must be a simple logic for most programmers but i am not able to figure it out.
I have 2 datetimepicker on my windows form
datetimepicker 1 = fromdate
datetimepicker 2 = todate
the from date and to date i get from the below sql
SELECT MIN(TransDate) AS mindate, MAX(TransDate) AS maxdate
FROM dbo.EtimePunchDetail WHERE (EmpID = #empid)
fromdate = mindate and todate = maxdate
fromdate.mindate = mindate
todate.maxdate = maxdate ("So the user is only working with the selected date range")
i added two textboxes with search functionality that the user can enter the fromdate and todate into and it checks against the mindate and maxdate and if the user enters a date out of the range i set the message box to throw an error
I have an textbox changed even that has the following query:
private void Min_TextChanged(object sender, EventArgs e)
{
DateTime date = DateTime.Parse(Min.Text);
if (date < DateTime.Parse(AvailableMin.Text))
{
MessageBox.Show("The Date you entered is either out of range or an invalid format");
}
else
{
FromDate.MinDate = date;
FromDate.Value = date;
}
}
private void Max_TextChanged(object sender, EventArgs e)
{
DateTime date = DateTime.Parse(Max.Text);
if (date > DateTime.Parse(AvailableMax.Text))
{
MessageBox.Show("The Date you entered is either out of range or an invalid format");
}
else
{
ToDate.MaxDate = date;
ToDate.Value = date;
}
}
But as i change the text the textchanged event gets fired with the message and is not letting me change the date or it says it is an invalid date. i want to be able to enter a date and then the textchanged should check to see if the date entered is not inrange how can i do that??
here is a visual representation for what i am asking for:
More Code on how i am getting the min and max date and the other things i am doing with those values i should have included this in my question before i apologize i thing the datetimepicker validation is interfering with the textbox validation
Min and Max Value
private void mindateset() // fill the listbox of values of mindate and maxdate
{
if (Employee.SelectedValue != null)
{
if (Employee.SelectedValue.ToString().Trim().Length > 0)
{
try
{
using (MSSQL.SqlConnection connection = new MSSQL.SqlConnection(constr))
{
timepunchnew = new EtimeHistoryDataSet();
connection.Open();
using (MSSQL.SqlCommand command = new MSSQL.SqlCommand("SELECT MIN(TransDate) AS mindate, MAX(TransDate) AS maxdate FROM dbo.EtimePunchDetail WHERE (EmpID = #empid)", connection))
{
MSSQL.SqlParameter myminparam = new MSSQL.SqlParameter();
myminparam.Direction = ParameterDirection.Input;
myminparam.ParameterName = "#empid";
myminparam.Value = Employee.SelectedValue;
command.Parameters.Add(myminparam);
MSSQL.SqlDataAdapter myadapter = new System.Data.SqlClient.SqlDataAdapter();
myadapter.SelectCommand = command;
myadapter.Fill(timepunchnew, "Mindate");
AvailableMin.DataSource = timepunchnew.Mindate;
AvailableMin.DisplayMember = "mindate";
AvailableMax.DataSource = timepunchnew.Mindate;
AvailableMax.DisplayMember = "maxdate";
FromDate.MinDate = DateTime.Parse(AvailableMin.Text);
FromDate.Value = FromDate.MinDate;
ToDate.MaxDate = DateTime.Parse(AvailableMax.Text);
ToDate.Value = ToDate.MaxDate;
Min.Text = FromDate.MinDate.ToString("d");
Max.Text = ToDate.MaxDate.ToString("d");
}
}
}
catch (Exception) { /*Handle error*/ }
}
}
}
Validation on the datetimepicker values
private void FromDate_ValueChanged_1(object sender, EventArgs e)
{
if (empchanging == false)
{
if (FromDate.Value > ToDate.Value)
{
// MessageBox.Show("From Date Cannot Be Greater Than To Date");
if (DialogResult.OK == MessageBox.Show("From Date Cannot Be Greater Than To Date"))
{
FromDate.MinDate = DateTime.Parse(AvailableMin.Text);
FromDate.Value = FromDate.MinDate;
}
}
}
}
private void ToDate_ValueChanged_1(object sender, EventArgs e)
{
if (empchanging == false)
{
if (ToDate.Value < FromDate.Value)
{
//MessageBox.Show("To Date Cannot Be Less Than From Date");
if (DialogResult.OK == MessageBox.Show("To Date Cannot Be Less Than From Date"))
{
ToDate.MaxDate = DateTime.Parse(AvailableMax.Text);
ToDate.Value = ToDate.MaxDate;
}
}
}
}
Validating Available date range for empty string
private void AvailableMin_SelectedIndexChanged(object sender, EventArgs e)
{
if (AvailableMin.Text == string.Empty)
{
textBox2.Visible = true;
textBox2.Text = "There is no From Date available for this particular user";
}
else
{
textBox2.Visible = false;
}
}
private void AvailableMax_SelectedIndexChanged(object sender, EventArgs e)
{
if (AvailableMax.Text == string.Empty)
{
textBox1.Visible = true;
textBox1.Text = "There is no To Date available for this particular user";
}
else
{
textBox1.Visible = false;
}
}
I tried the below solution
private void Min_TextChanged(object sender, EventArgs e)
{
DateTime date;
if (!DateTime.TryParse(Min.Text, out date))
{
formerrorprovider.SetError(this.Min,"The Date you entered is in invalid format");
}
else if (date < DateTime.Parse(AvailableMin.Text))
{
formerrorprovider.SetError(this.Min, "The Date you entered is either out of range");
}
else
{
formerrorprovider.SetError(this.Min, string.Empty);
FromDate.MinDate = date;
FromDate.Value = date;
}
it accepts the date i enter but is interfering with the datetimepicker validation.
PLZ HELP
as a possible UI solution: don't show a MessageBox if date is invalid but add an ErrorProvider control to Form and set errors description to Max and Min textboxes. Error provider will show Error icon if there are incorrect data and hide it when input is acceptable
private void Max_TextChanged(object sender, EventArgs e)
{
DateTime date;
if (!DateTime.TryParse(Max.Text, out date))
{
formErrorProvider.SetError(this.Max, "The Date you entered is in invalid format");
}
else if (date > DateTime.Parse(AvailableMax.Text))
{
formErrorProvider.SetError(this.Max, "The Date you entered is out of range");
}
else
{
formErrorProvider.SetError(this.Max, string.Empty);
ToDate.MaxDate = date;
ToDate.Value = date;
}
}
Your code is doing exactly what you asked it to do: it is validating the value any time the text has changed.
If this is not the behavior you want, then don't do that!
You may prefer, for example, to validate the value on the Leave or LostFocus event. Alternatively, you can leverage the existing validation model in the Control class and put your validation in a method that is an event handler for the Validating event (which is raised between the Leave and LostFocus events).
The other suggestion – to present the user feedback in a less disruptive way – is also a very good suggestion. That would be more user-friendly in general, at the possible expense of making the user feedback more subtle and easier for the user to overlook.
I already can make the login for user, so if user type their username or password wrongly in textbox, the message label that says "Invalid username or password" appear. But, i want to when user type a single character or number in textbox when the message label is appear, the message label will not visible to user (visible = false) as user already type a single character or number in textbox. But the message label didn't disappear when user type a single character or number.
This is the code:
private void CheckTextBox(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text))
{
label5.Visible = true;
}
else
{
label5.Visible = false;
}
}
And here is the image:
Below image is when user type wrongly (the username or password), the message label appear:
Below image is when user type a single character or number, but the message label still at there
My question is: How do i set the message label to not show when user type a single character or number in the textbox?
Any help?
Your answer will be great appreciated!
Thank you!
Problem : You have not wiredup the CheckTextBox() method for both TextBox1 and TextBox2 TextChanged Event.
Solution : in your Form_Load WireUp the CheckTextBox() method for the Textbox1 and TextBox2 TextChanged Event as below:
private void Form1_Load(object sender, EventArgs e)
{
textBox1.TextChanged += new System.EventHandler(this.CheckTextBox);
textBox2.TextChanged += new System.EventHandler(this.CheckTextBox);
}
Suggestion : i think string.IsNullOrWhiteSpace() is more appropriate as it would also check for Whitespace in addition to null and Empty strings.
Try This:
private void CheckTextBox(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(textBox1.Text) || string.IsNullOrWhiteSpace(textBox2.Text))
{
label5.Visible = true;
}
else
{
label5.Visible = false;
}
}
This line is checking if either textbox has information in it.
if (string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text))
Change the || to && and then the label will only be shown when BOTH textboxes do not have any data.
If I understand you correctly, try this:
private void CheckTextBox(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox1.Text) && string.IsNullOrEmpty(textBox2.Text))
{
label5.Visible = true;
}
else
{
label5.Visible = false;
}
}
If you change || to && then label5 will be visible only if both textboxes are empty.
if (string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text))
Try this..use && instead of ||
private void CheckTextBox(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox1.Text) && string.IsNullOrEmpty(textBox2.Text))
{
label5.Visible = true;
}
else
{
label5.Visible = false;
}
}
Check this code, Should be call this OnTextChanged="CheckTextBox" on your textbox
protected void CheckTextBox(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox1.Text) && string.IsNullOrEmpty(textBox2.Text))
{
label5.Visible = true;
}
else
{
label5.Visible = false;
}
}
<asp:TextBox ID="TextBox1" runat="server" OnTextChanged="CheckTextBox"></asp:TextBox>
In winforms there are different controls like textbox,combobox dropdown. In these some fields are mandatory and some are not, so while validating all fields, if there is some error then it shows error and returns to that that method again, and all the control value gets clear. I want to keep those control value in form as such if error comes. How do I do this? Maybe I can check all control values not null, or something like this, but for not mandatory can't check this. How do I do it? Here is the code. I am displaying errors like this.
private void button1_Click(object sender, EventArgs e)
{
string title = txtTitle.Text;
string fname = txtFirstName.Text;
string mname = txtMiddleName.Text;
string lname = txtLastName.Text;
int feeAmount;
if (txtTitle.Text.Equals(""))
{
MessageBox.Show("Please Enter Title");
return;
}
if (txtFirstName.Text.Equals(""))
{
MessageBox.Show("Please Enter First Name");
return;
}
if (fname.Length < 3)
{
MessageBox.Show("Firstname must contain atleast 3 Character");
return;
}
if (txtLastName.Text.Equals(""))
{
MessageBox.Show("Please Enter Last Name");
return;
}
if (rdoPercent.Checked == false && rdoPerPatnt.Checked == false)
{
MessageBox.Show("Please Select Fee Unit");
return;
}
if(db.NewDrMaster(title,fname,mname,lname,txtRegistrationNo.Text,txtSpeciality.Text, txtContact1.Text,landlineno,cmbCity.SelectedItem.ToString(),Address,txtPincode.Text,txtEmailID.Text,feeUnit,txtFee.Text,DrType,Display))
{
MessageBox.Show("Doctor Refernced By added Successfully");
}
else
{
MessageBox.Show("failed");
}
}