TextBox validating doesn't work - c#

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

Related

How to prevent auto firing RadioButtonList indexchange event?

I have a radioButton list and I want to set 0 as default index.
But,when page is posted by other button ,radiobuttonListChanged event is firing automaticly.
What should I do ?
protected void Page_Load (object sender, EventArgs e)
{
rblList.DataSource = MyDataSource();
rblList.DataBind ();
if (!IsPostBack)
{
rblAccounts.SelectedIndex = 0;
}
}
protected void rbl_Changed (object sender, EventArgs e)
{
Response.Write("Change Event fired");
}
In rbl_Changed event Write following code probably will help you out.
rbl.changed-= rbl_Changed;
rbl.changed = false;
rbl.changed+= rbl_Changed;

Indirect reference to a button

I'm having this code:
private void b9_Click(object sender, EventArgs e)
{
b9.Enabled = false;
color = 8;
}
The problem is that i'm having a lot of buttons for disabling. Is there a chance i can use something like:
this.Enabled=false;
Probably that is what you want
private void OnClick(object sender, EventArgs e)
{
if( sender is Button )
{
Button button = (Button)sender;
button.Enabled = false;
}
}
Use this routine for every button you need to disable on click.
It is known as single event handler for multiple controls. Just put following event handler for your buttons as many as you like.
public void Button_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
button.IsEnable = false;
// If you want to access text in the button
... = button.Content as object;
}
private void OnClick(object sender, EventArgs e)
{
Button btn = sender as Button; // if sender is not a Button, btn will be null
if (btn != null)
{
btn.Enabled = false;
}
}
If you want to apply the same behaviour to any clickable control, you can use Control class instead of Button. Button inherits from Control and the property Enabled is defined in Control class.
private void OnClick(object sender, EventArgs e)
{
Control ctrl = sender as Control; // if sender is not a Control, ctrl will be null
if (ctrl != null)
{
ctrl .Enabled = false;
}
}
Also, if you want to go one step further, you can create a method that disables the clicked control. Something like this:
private void DisableControl(object sender)
{
Control ctrl = sender as Control;
if (ctrl != null)
{
ctrl.Enabled = false;
}
}
Then, you can call this method from the Click even handler like this:
private void OnClick(object sender, EventArgs e)
{
DisableControl(sender);
}

How to pass button object to function

I have several buttons to click, and all the same function (that I want to create), they just differ by controller's name. For example:
private void markX()
{
buttonName.Text = "X";
buttonName.ForeColor = System.Drawing.Color.Red;
}
How can I pass the button object that that is modified in the function into the function's parameters?
Make it a Click event handler, attach it to each button, and use the sender parameter as the button to change.
void button_Click(Object sender, EventArgs e)
{
var button = sender as Button;
if(button != null)
{
button.Text = "X";
button.ForeColor = System.Drawing.Color.Red;
}
}
You don't need to pass the name of the button, you just need to pass an object of type button as an argument to your method.
private void markX(Button b)
{
b.Text = "Text";
b.Foreground = System.Drawing.Color.Red;
}
Use "sender":
private void Button_click(object sender, EventArgs e)
{
((Button)sender).Text = "X";
}
sender holds instance of event caller.
The click handler for the button click event has the following objects.
Object sender
EventArgs e
This will give you the name of the Button that was clicked, and just pass that to your function.
((Button)sender).Tag
Here is some sample code
private void Button_Clicked(Object sender, EventArgs e)
{
string name = ((Button)sender).Tag;
markX(name);
}

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

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

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

Categories

Resources