Why Doesn't Regex give a chance to input data? - c#

I have a event which doesn't give a any opportunity to input data in TextBox. When I'm trying to input data in Textbox, then Textbox doesn't give to do it:
private void Login_textbox_KeyPress(object sender, KeyPressEventArgs e)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(textbox1.Text, #"^[a-zA-Z]+$"))
e.Handled = true;
}
I just want to input data in TextBox which isn't digit or any symbols.

Try using the following code
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString() , #"^[a-zA-Z]+$"))
e.Handled = true;
}
Thanks!

It seems you are using c#.
Then steps you need to follow :
1) Set causesValidation property of your textbox to true
2) Set event listeners for causes validation
myTextBox1.Validating +=
new System.ComponentModel.CancelEventHandler(myTextBox1_Validating);
myTextBox1.Validated +=
new System.EventHandler(myTextBox1_Validated);
3) Implement these event hadler functions
private void myTextBox1_Validating(object sender,System.ComponentModel.CancelEventArgs e)
{
if(!CheckIfTextBoxNumeric(myTextBox1))
{
myLabel.Text = "Has to be numeric";
e.Cancel = true;
}
}
private void myTextBox1_Validated(object sender,System.EventArgs e)
{
myLabel.Text = "Validated first control";
}
If you instead want to use maskedTextBox refer http://msdn.microsoft.com/en-us/library/ms234064(v=vs.80).aspx

Related

Can I use AcceptButton() to move to the next textbox?

I'm doing a simple login screen and I have already implemented a simple method in the password textbox to simulate the 'OK" button being clicked:
private void textpwd_TextChanged(object sender, EventArgs e)
{
this.AcceptButton = btnLogin;
}
can I use the same method in the username textbox to move to the password textbox?
private void textusername_TextChanged(object sender, EventArgs e)
{
this.AcceptButton = textpassword.Focus();
}
private void textusername_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode==Keys.Enter)
textpassword.Focus(); // or SendKeys.Send("{Tab}");
}
Not to write a specific code for each of your TextBox(es) it's better to simulate the Tab key press behavior.
Edit the Tab order via View -> TabOrder based on your needs.
Set the following method for all of your form controls KeyDown event
private void AllControls_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
SendKeys.Send("{TAB}");
e.SuppressKeyPress = true;
}
}

C# - Disable button if string empty or has whitespace?

I just started learning C#.
Here's my code:
private void button1_Click(object sender, EventArgs e)
{
object Nappi1 = ("Nice button");
MessageBox.Show(Nappi1.ToString());
}
I got a textbox, that should disable the button1 if empty or whitespace.
I already got it working in some level, but it checks the state of the textbox on button1_Click.
private void button1_Click(object sender, EventArgs e)
{
if (textBox1 = "")
{
button1.enabled = false;
}
else
{
button1.enabled = true;
object Nappi1 = ("Nice button");
MessageBox.Show(Nappi1.ToString());
}
}
Fictional example:
if (textBox1 = "" or textBox1 = whitespace[s])
How could I make it check the state of the textbox onLoad (as soon as the program starts)?
How could I make it check if (multiple) whitespace, and can I write it to the same if -statement?
Please keep it simple.
To answer exactly the question title, Shorter, clearer:
button1.Enabled = !string.IsNullOrWhiteSpace(textBox1.Text);
Replace your if-else with this, if it is only a string:
if (string.IsNullOrWhiteSpace(textBox1)) {
button1.enabled = false;
}
else {
button1.enabled = true;
...
}
or use textBox1.Text if it is really a Textbox use this:
if (string.IsNullOrWhiteSpace(textBox1.Text)) {
button1.enabled = false;
}
else {
button1.enabled = true;
...
}
You want String.IsNullOrWhiteSpace:
if (String.IsNullOrWhiteSpace(textBox1.Text)) {
button1.enabled = false;
}
You originally had:
if (textBox1 = "") {
button1.enabled = false;
}
textbox is the control, you need to use the Text property which refers to the string literal inside the textbox control. Also in C# = is an assignment, you ideally would want == which is used to compare.
If you're not using .NET 4 or .NET 4.5 you can use:
String.IsNullOrEmpty
This can be done by using hooking an event handler to text-box text changed event.
Steps:
Attach an event handler for text-box (on text changed)
Inside the text changed event handler enable / disable the button.
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(textBox1.Text))
button1.Enabled = false;
else
button1.Enabled = true;
}
By default disable the button in InitializeComponent method of form
button1.Enabled = false;
In the textBox1 text changed event, right this code:
button1.Enabled = !string.IsNullOrWhiteSpace(textBox1.Text);
string.IsNullOrWhiteSpace("some text") will check if the text is none or just a wightspaces
if this is true you will set button1.Enabled to false.

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

No overload for 'textBox1_TextChanged' matches delegate 'System.EventHandler'

Hello Everyone. This is my first Program and within in 5 minutes I have a error. I've only started to today using C#, so I know I should be really looking around, but I didn't think there was a problem with what I was doing.
My Program is a Generator
depending on what a user picks or types in all the textboxes depends on the outlook of the generated code.
I have two text boxes named: textBox1, and GeneratedCode
When I press checkBox1 it allows textbox1 to be used.
When I press my button it created a string "Testing" (which was to make sure I did it right).
When I pressed F5 to test my build it came back with this error:
No overload for 'textBox1_TextChanged' matches delegate 'System.EventHandler'
I do not know what this means.
Here's my code:
public void checkBox1_CheckedChanged(object sender, EventArgs e)
{
switch (checkBox1.Checked)
{
case true:
{
textBox1.Enabled = true;
break;
}
case false:
{
textBox1.Enabled = false;
break;
}
}
}
private void textBox1_TextChanged()
{
}
public void button1_Click(object sender, EventArgs e)
{
GenerateBox.Text += "Testing";
}
private void GenerateBox_Generated(object sender, EventArgs e)
{
}
This is form1.designer which is in C++:
//
// textBox1
//
this.textBox1.Enabled = false;
this.textBox1.Location = new System.Drawing.Point(127, 3);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(336, 20);
this.textBox1.TabIndex = 1;
this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged); //Error
//
// GenerateBox
//
this.GenerateBox.Enabled = false;
this.GenerateBox.Location = new System.Drawing.Point(84, 6);
this.GenerateBox.MaxLength = 1000000;
this.GenerateBox.Multiline = true;
this.GenerateBox.Name = "GenerateBox";
this.GenerateBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.GenerateBox.Size = new System.Drawing.Size(382, 280);
this.GenerateBox.TabIndex = 1;
this.GenerateBox.TextChanged += new System.EventHandler(this.GenerateBox_Generated);
The function textbox1_textChanged should have two arguments as below to be accepted by EventHandler in this case
textBox1_TextChanged(object sender, EventArgs e)
Your textbox1_TextChanged method does not match what is expected of the System.EventHandler delegate. It should be
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
The compiler is telling you exactly what is wrong, you don't have an EventHandler called textBox1_TextChanged.
Change your textBox1_TextChanged method to read:
private void textBox1_TextChanged(object sender, EventArgs e)
{
//Why are you handling this event if you aren't actually doing anything here???
}
For the rest of my concern with this question, please refer to the commented portion of my code example.
If you didn't mean to add a handler for this event, just remove the following from your designer code:
textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged);

TextBox validating doesn't work

I have two textboxes. I need to validate them before taking any other action.
private ErrorProvider _errorProviderEmail = new ErrorProvider();
private ErrorProvider _errorProviderPass = new ErrorProvider();
public FormLogin()
{
InitializeComponent();
textBoxEmail.Validating += TextBoxEmailValidating;
textBoxPass.Validating += TextBoxPassValidating;
textBoxEmail.Validated += TextBoxEmailValidated;
textBoxPass.Validated += TextBoxPassValidated;
textBoxEmail.Text = "";
textBoxPass.Text = "";
}
void TextBoxPassValidated(object sender, EventArgs e)
{
_errorProviderPass.SetError(textBoxPass, "");
}
void TextBoxEmailValidated(object sender, EventArgs e)
{
_errorProviderEmail.SetError(textBoxEmail, "");
}
void TextBoxPassValidating(object sender, System.ComponentModel.CancelEventArgs e)
{
if (!string.IsNullOrEmpty(textBoxPass.Text)) return;
e.Cancel = true;
_errorProviderPass.SetError(textBoxPass,"Password is required!");
}
void TextBoxEmailValidating(object sender, System.ComponentModel.CancelEventArgs e)
{
if (!string.IsNullOrEmpty(textBoxEmail.Text)) return;
e.Cancel = true;
_errorProviderEmail.SetError(textBoxEmail, "Email address is required!");
}
The problem is that only validating event for textBoxEmail is triggered, what could be wrong here, and why the validating event for textBoxPass never fires?
The individual TextBox controls only validate when they lose their focus.
Try calling the form's ValidateChildren() function to force each control to call their validation handlers:
private void button1_Click(object sender, EventArgs e) {
if (this.ValidateChildren()) {
this.Close();
}
}
Also, you only need one ErrrorProvider component.
The Validating event is raised only when the control that receives the focus has the CausesValidation property set to true.
For example, if you have written code in TextBox1's Validating event, and you click the OK button (CausesValidation = true) then the Validating event is raised, but if you click the Cancel button (CausesValidation = false) then the Validating event is not raised.
Source on CodeProject

Categories

Resources