How can add rules to textBox textchanged event? - c#

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";
}
}

Related

C#- Confirm, Password and Email text box shows me message box when I enter first character

//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");
}
}

Simple login screen with user name and password

I'm trying to create a simple login screen, which has 2 textboxes and 1 button. When strings i've insterted in the first textbox (username) and the second textbox (password) matches the strings i've defined before, the buttons Enabled propertie should become True and when clicked, it should open another form, here's the code i've written so far:
public partial class LogInScreen : Form
{
public LogInScreen()
{
InitializeComponent();
string lietotajvards = "user";
string parole = "user";
if (textBox1.Text == lietotajvards && textBox2.Text == parole)
{
button1.Enabled = true;
}
else
{
button1.Enabled = true;
}
}
private void button1_Click(object sender, EventArgs e)
{
Form1 f1 = new Form1();
this.Hide();
f1.Show();
}
}
The thing is that with my code it doesn't work as expected and the button is enabled all the time. Where's the problem?
Your code will only execute once when the form is initialized, you have to make use of a textchanged event on textbox1 and textbox2, thereafter you can use the code you wrote to check if the button needs to be enabled. In the else you must disable the button.
Text changed event handlers:
void textBox1_TextChanged(object sender, EventArgs e)
{
handleLoginButton();
}
void textBox2_TextChanged(object sender, EventArgs e)
{
handleLoginButton();
}
Enable/disable button:
private void handleLoginButton(){
string lietotajvards = "user";
string parole = "user";
if (textBox1.Text == lietotajvards && textBox2.Text == parole)
{
button1.Enabled = true;
}
else
{
button1.Enabled = false;
}
}
The constructor only runs once for the form, you need to handle the text changed events for the input controls and then re-evaluate your condition again.
Also it should go without saying (although it is being said here) that this is a terrible way to handle logging in to an application.

Check if user type a single character or number in textbox c#

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>

C# - Highlight wrong controls when validating

I am trying to validate windows form with try catch and so far I succeeded. My goal is when someone forgot to fill the gap or put in incorrect entry, catch returns messagebox with a warning. Now I also have Validating event on every control I want to validate so when somebody leave it empty or in incorrect format it will show the error next to the control. That seems ok so far (for me, at least) but my issue is, that if user doesn't even click to one box it only shows message box, but it won't highlight wrong controls.
Below is my code:
private void createButton_Click(object sender, EventArgs e)
{
try
{
Book newBook = new Book(titleBox.Text, authBox.Text, Convert.ToInt32(yearBox.Text), Convert.ToInt32(editBox.Text), pubComboBox.Text, descBox.Text);
bookList.Add(newBook);
booklistListBox.DataSource = bookList;
}
catch (FormatException)
{
MessageBox.Show("You probably missed a gap or put in incorrect form");
}
}
and those validating events:
private void titleBox_Validating(object sender, CancelEventArgs e)
{
if (titleBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(titleBox, "Title is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(titleBox, "");
}
}
private void authBox_Validating(object sender, CancelEventArgs e)
{
if (authBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(authBox, "Author is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(authBox, "");
}
}
private void yearBox_Validating(object sender, CancelEventArgs e)
{
if (yearBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(yearBox, "Year is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(yearBox, "");
}
}
private void editBox_Validating(object sender, CancelEventArgs e)
{
if (editBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(editBox, "Edition is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(editBox, "");
}
}
private void pubComboBox_Validating(object sender, CancelEventArgs e)
{
if (pubComboBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(pubComboBox, "Publisher is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(pubComboBox, "");
}
}
private void descBox_Validating(object sender, CancelEventArgs e)
{
if (descBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(descBox, "Description is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(descBox, "");
}
}
So is there way to, I don't know, change focus or something like that, forced with pressing the create button?
Thank You
Try using ValidateChildren():
private void createButton_Click(object sender, EventArgs e)
{
bool gotIssues = this.ValidateChildren();
if (gotIssues)
{
// someone didn't validate well...
}
}
So, the issue here is that you want to have it highlight in either of two scenarios:
1) When you leave the field and its contents are invalid (empty in this case)
2) When you click the create button and the field in question has invalid contents
And so I would create a single textBox_checkIfEmpty(object sender, EventArgs e) method:
private void textBox_checkIfEmpty(object sender, EventArgs e)
{
var asTb = sender as TextBox;
if (asTb != null && asTb.Text.Trim() == String.Empty)
{
errorProvider.SetError(asTb, "I'll leave it to you to abstract the error message appropriately");
e.Cancel = true;
}
else
{
errorProvider.SetError(asTb, "");
}
}
Then, you can set this method as the handler for your Validate event on your desired required controls, and you can also call the same method from the create button's handler, looping through the required TextBox instances and executing the method on each.
UPDATE
J. Hudler's ValidateChildren solution would be a more (developer) efficient tail to mine, as opposed to looping through the desired controls. That said, if the form has many children, and you only need to validate several, it might be helpful to loop still. Just depends on your specific scenario. My only other question is whether or not ValidateChildren is infinitely recursive, or if it only goes one level down (immediate children rather than all descendants).
the event validating for control call when the mouse click on the control and then leave it from the control. In your case when the user does not click on the control it will not trigger the validating event. U can do this by making your own function and call them on creat event.
private void button1_Click(object sender, EventArgs e)
{
textBox1_Validating(sender);
}
public void textBox1_Validating(object sender)
{
MessageBox.Show("validating");
errorProvider1.SetError(textBox1, "provide");
}

Controling if condition in text change function

I want if a user type the character "a" in textbox, message box with message "Ok" displays, and then textbox should clear.But I am facing the problem that when I type "a" message "Ok" is displays and along with message "No" is also displays.But when I remove the statment of clear then all goes good. Please tell me how to overcome this problem ?
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text == "a")
{
textBox1.Text = "";
MessageBox.Show("Ok");
}
else
{
MessageBox.Show("No");
}
}
It's because the Text="" triggered the TextChanged one more time. Use some flag like this:
bool suppressTextChanged;
private void textBox1_TextChanged(object sender, EventArgs e) {
if(suppressTextChanged) return;
if (textBox1.Text == "a") {
suppressTextChanged = true;
textBox1.Text = "";
suppressTextChanged = false;
MessageBox.Show("Ok");
} else {
MessageBox.Show("No");
}
}
NOTE: The code above supposes you want to check against a string ("a" is just an example). If you want to check against a character. Use the KeyPress event instead.
You're using the TextChanged event of the textbox. When you change the text manually the TextChanged event runs again and this time the else expression runs.
private void textBox1_TextChanged(object sender, EventArgs e)
{
if(textBox1.Text != "")
if (textBox1.Text == "a")
{
textBox1.Text = "";
MessageBox.Show("Ok");
}
else
{
MessageBox.Show("No");
}
}
That is because when you set textBox1.Text = ""; the event textBox1_TextChanged is raised one more and there is not a letter 'a' in the textbox and therefore a messasge box with "No" is also displayed.
You need to check if the change in textBox1.Text was from the user, or from you. "No" is displayed because you change the text to something ("") that is not "a". You could keep a boolean flag that indicates whether you want to react on the change:
bool changedByCode = false;
private void textBox1_TextChanged(object sender, EventArgs e)
{
if(changedByCode) return;
if (textBox1.Text == "a")
{
changedByCode = true;
textBox1.Text = "";
changedByCode = false;
MessageBox.Show("Ok");
}
else
{
MessageBox.Show("No");
}
}
You should handle KeyUp event
public Form1()
{
InitializeComponent();
textBox1.KeyUp+=new KeyEventHandler(textBox1_KeyUp);
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (textBox1.Text == "a")
{
textBox1.Text = "";
MessageBox.Show("Ok");
}
else
{
MessageBox.Show("No");
}
}
That's because the textBox1.Text = "" calls textBox1_TextChanged again.

Categories

Resources