C# winform - equivalent of InputScope - c#

Is there a property in Winform (.Net 4.0) that is equivalent to InputScope in UWP?

No I do not believe so. You need to use the Validating event
Such as if you want to assure the textbox contains an email you would do something like this:
private void textBox1_Validating(object sender,
System.ComponentModel.CancelEventArgs e)
{
string errorMsg;
if(!ValidEmailAddress(textBox1.Text, out errorMsg))
{
// Cancel the event and select the text to be corrected by the user.
e.Cancel = true;
textBox1.Select(0, textBox1.Text.Length);
// Set the ErrorProvider error with the text to display.
this.errorProvider1.SetError(textBox1, errorMsg);
}
}
private void textBox1_Validated(object sender, System.EventArgs e)
{
// If all conditions have been met, clear the ErrorProvider of errors.
errorProvider1.SetError(textBox1, "");
}
public bool ValidEmailAddress(string emailAddress, out string errorMessage)
{
// Confirm that the email address string is not empty.
if(emailAddress.Length == 0)
{
errorMessage = "email address is required.";
return false;
}
// Confirm that there is an "#" and a "." in the email address, and in the correct order.
if(emailAddress.IndexOf("#") > -1)
{
if(emailAddress.IndexOf(".", emailAddress.IndexOf("#") ) > emailAddress.IndexOf("#") )
{
errorMessage = "";
return true;
}
}
errorMessage = "email address must be valid email address format.\n" +
"For example 'someone#example.com' ";
return false;
}

Related

How to validate textbox value while user enters and display error message?

So, I have to code for a method that validates whether the string that saves name contains alphabets only, no numbers. The validation of textbox values should apply when the user enters by textchanged event before submitting the form and display an error message of red color on the label. My code works but the problem is when I enter a numeric number in text box, the label displays error which stays even when I delete the text box value and enter the alphabetic string.
I have declared a method which assign error string to label, and is called if regular expression does not match with the text box input, during text changed event.
public void Validator()
{
Calculate_Salary.Enabled = false;
label4.Text = "Please enter only alphabetical letters";
}
private void _Name_TextChanged(object sender, EventArgs e)
{
Regex pattern = new Regex("/^[A-Za-z]+$/");
string name = _Name.Text;
if (pattern.IsMatch(name))
{
Calculate_Salary.Enabled = true;
label4.Text = "";
}
else
{
Validator();
}
}
Just clear the textbox before you validate:
public void Validator()
{
Calculate_Salary.Enabled = false;
label4.Text = "Please enter only alphabetical letters";
}
private void _Name_TextChanged(object sender, EventArgs e)
{
label4.Text = "";
Regex pattern = new Regex("/^[A-Za-z]+$/");
string name = _Name.Text;
if (pattern.IsMatch(name))
{
Calculate_Salary.Enabled = true;
}
else
{
Validator();
}
}
Your Regex comparison is wrong try this code:
public void Validator()
{
Calculate_Salary.Enabled = false;
label4.Text = "Please enter only alphabetical letters";
}
private void _Name_TextChanged(object sender, EventArgs e)
{
label4.Text = "";
string name = _Name.Text;
if (Regex.IsMatch(name, #"^[a-zA-Z]+$"))
Calculate_Salary.Enabled = true;
else
Validator();
}
I changed the validation code. It seems to work now.
private void _Name_TextChanged(object sender, EventArgs e)
{
label4.Text = string.Empty;
string name = _Name.Text;
if (Regex.IsMatch(_Name.Text, "^[a-zA-Z]+$") || _Name.Text=="")
{
Calculate_Salary.Enabled = true;
}
else
{
Calculate_Salary.Enabled = false;
label4.Text = Validator();
}
}

c# winforms Error provider issue

I am stuck with trying to display two error mssgs for one textbox
1. if textbox empty -mssg please enter value..this works ok for me
2.text box to accept only numeric values
Any help much appreciated
thank you
here is my code: scroll down for actual errorprovider attempt
ListClass lc = new ListClass();
private void btnAddStu_Click(object sender, EventArgs e)
{
string title = cboTitle.SelectedItem.ToString();
string fname = txtFname.Text;
string lname = txtLname.Text;
string dob = dtpDOB.Text;
int stuId = int.Parse(txtSid.Text);
string status = cboStatus.SelectedItem.ToString();
string phone = txtPhone.Text;
string email = txtEmail.Text;
lblRemarks.Text = lc.AddStudent(title, fname, lname, dob, stuId, status, phone, email);
txtEmail.Clear();
txtFname.Clear();
txtLname.Clear();
txtPhone.Clear();
txtSid.Clear();
Errorprovide code:
private void txtSid_Validating(object sender, CancelEventArgs e)
{
bool can = false;
int sid = 0;
if (string.IsNullOrEmpty(txtSid.Text))
{
ep1.SetError(txtSid, "Please Enter Student ID");
can = true;
}
else if (int.TryParse(txtSid.Text, out sid))
{
ep1.SetError(txtSid, "Student ID must be a number");
can = true;
}
e.Cancel = can;
}
Instead of using your event, you should try this
private void textbox_KeyPress(object sender, KeyPressEventArgs e)
{
try
{
if (e.KeyChar == '.' || e.KeyChar == Convert.ToChar(Keys.Back))
{
if (e.KeyChar == '.' && textIIC.Text.Contains('.'))
{
e.Handled = true;
}
return;
}
e.KeyChar = Char.ToUpper(e.KeyChar);
decimal isNumber = 0;
e.Handled = !decimal.TryParse(e.KeyChar.ToString(), out isNumber);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This code I provide above only allowed you to input number, nothing but number :)

Only one message box is popped up after validating the 2 validations

abstract class User
{
public string Username;
public string Password;
public virtual bool Validate(string username, string password)
{
Username = "";
Password = "";
if (password == Password && username == Username)
{
MessageBox.Show("Incorrect password or username");
return true;
}
else
{
return false;
}
}
form code:
private void btnSubmit_Click(object sender, EventArgs e)
{
UserAdmin admin = new UserAdmin();
UserEmployee empp = new UserEmployee();
bool validateAdmin = admin.Validate(txtUsername.Text, txtPassword.Text);
bool validateEmpp = empp.Validate(txtUsername.Text, txtPassword.Text);
if (validateAdmin==true || validateEmpp == true )
{
this.Hide();
// Create a new instance of the options class
Options opt = new Options();
opt.Closed += (s, args) => this.Close();
// Show the settings form
opt.Show();
}
When the first validation is false it keeps checking the second validation as well.By doing so 2 message boxes are being popped up.
EDIT:
Can you show only one message box instead of 2? it only shows the message box if the username or password is incorrect
You can combine validations in conditional expression:
if(admin.Validate(txtUsername.Text, txtPassword.Text) && empp.Validate(txtUsername.Text, txtPassword.Text))
{
... // is ok
}
else
{
... // when either Validate from left to right is not ok
}
This way if admin.Validate return false, then empp is not validated.
I would say that the standard way to stop execution of the code - is throwing an exception. So what You could do - is throw a 'ValidationExceptio' and implement appropriate ex handlers
To stop showing two message boxes, Remove the message box from method and include it into the click event. So the method will be like this:
public virtual bool Validate(string username, string password)
{
if (password == Password && username == Username)
{
return true;
}
else
{
return false;
}
}
And the click event will be like :
private void btnSubmit_Click(object sender, EventArgs e)
{
UserAdmin admin = new UserAdmin();
UserEmployee empp = new UserEmployee();
bool validateAdmin = admin.Validate(txtUsername.Text, txtPassword.Text);
bool validateEmpp = empp.Validate(txtUsername.Text, txtPassword.Text);
if (validateAdmin)
{
MessageBox.Show("Successfylly login as Admin");
//operation here
}
else if (validateEmpp)
{
MessageBox.Show("Successfylly login as " + txtUsername.Text);
//operation here
}
else { MessageBox.Show("Incorrect password or username"); }
}

C# Displaying error messages by completing a simple registration form

I'm new about C#, I learnt C programmation for one year now.
I created a Window Form which asks the user to complete a registration form.
My registration form
I'd like to display an error message below the buttons when a field is not filled or a field isn't well used.
I used this basic code :
private void button1_Click(object sender, EventArgs e)
{
if (!isOkay(userTextBox.Text))
{
label5.Text = "Please, enter an username.";
label5.Visible = true;
}
else if (!isOkay(mailTextBox.Text))
{
label5.Text = "Please, enter a mail address.";
label5.Visible = true;
}
else if (!confirmMailTextBox.Text.Equals(mailTextBox.Text) || !isOkay(confirmMailTextBox.Text))
{
label5.Text = "Please, match both mails addresses.";
label5.Visible = true;
}
else if (!isOkay(passwordTextBox.Text))
{
label5.Text = "Please, enter a password.";
label5.Visible = true;
}
else
{
label5.Text = "Valid form, yay !";
label5.Visible = true;
}
}
private Boolean isOkay(string textBoxContent)
{
return (textBoxContent.Length > 0 || textBoxContent.Equals(null));
}
Are there any elegant or optimized ways to do it properly ? I found some Error providers, but apparently error providers open a pop-up, and I just want a "red error message below buttons".
Can you give me some help ? :)
Given a class like this
public class RequiredFieldsError
{
private List<string> errors;
public RequiredFieldsError()
{
errors = new List<string>();
}
public int Count
{
get{return errors.Count;}
}
public void AddField(string errorField)
{
errors.Add(errorField);
}
public override string ToString()
{
if(errors.Count == 0)
return string.Empty;
else
{
string fields = string.Join(Environment.NewLine, errors);
fields = "The following fields contains errors:" + Environment.NewLine + fields;
return fields;
}
}
}
then you could change your code to
private void button1_Click(object sender, EventArgs e)
{
RequiredFieldsError rfe = new RequiredFieldsError();
if (!isOkay(userTextBox.Text))
rfe.AddField("User name missing, Please, enter an username.";
if (!isOkay(mailTextBox.Text))
rfe.AddField("Email address missing, Please, enter a mail address.";
if (!confirmMailTextBox.Text.Equals(mailTextBox.Text) || !isOkay(confirmMailTextBox.Text))
rfe.AddField("Email address doesn't match the confirmation email");
if (!isOkay(passwordTextBox.Text))
rfe.AddField("Password missing, Please, enter a password.";
if(rfe.Count > 0)
{
// MessageBox.Show(rfe.ToString());
label5.Text = rfe.ToString()
label5.Visible = true;
}
}
This approach avoids the unnerving situation (for your user) when he/she receives an error message, he/she fixes it just to receive another error message at the next attempt to confirm the form.
Of course your label should be tall enough to show all the possible messages or just use a messagebox.
I suggest also to change your IsOkay function to
private Boolean isOkay(string textBoxContent)
{
return !string.IsNullOrWitheSpace(textBoxContent));
}
this will handle also a string composed just of one or more spaces. (not null and not length==0)
You can use ErrorProvider. It show's an error icon after your textbox.
For one of your textboxes for example:
if (!isOkay(userTextBox.Text))
{
errorProvider1.SetError(userTextBox "yourmessage");
}
else{
errorProvider1.Clear();
}
Link: http://www.dotnetperls.com/errorprovider

Add textbox data to an object after button click c#

I pass a custom Associate object into a field and I want to add user name and password to it after a button click event. The problem is I loose scope of the object in the button click event. How do I get around this? Here is the code I have so far...
public partial class frmCredentials : Form
{
public frmCredentials(Associate _associate)
{
InitializeComponent();
//Put in values for MES system and username
this.label1.Text = "Please enter your " + _associate.mesType + " password";
this.txtUsername.Text = _associate.userName;
//Change form color for MES system
if (_associate.mesType == "FactoryWorks")
{
this.BackColor = System.Drawing.Color.Aquamarine;
}
else
{
this.BackColor = System.Drawing.Color.Yellow;
}
}
private void btnOk_Click(object sender, EventArgs e)
{
//Make sure associate has filled in fields
if (this.txtUsername.Text == "" || this.txtPassword.Text == "")
{
MessageBox.Show("You must enter a Username and Password");
return;
}
this.Visible = false;
return ;
}
}
The solution is to create an instance field for your Associate object. And then set the instance field value in your constructor.
public partial class frmCredentials : Form
{
private Associate _associate;
public frmCredentials(Associate _associate)
{
InitializeComponent();
this._associate = _associate;
//Put in values for MES system and username
this.label1.Text = "Please enter your " + _associate.mesType + " password";
this.txtUsername.Text = _associate.userName;
//Change form color for MES system
if (_associate.mesType == "FactoryWorks")
{
this.BackColor = System.Drawing.Color.Aquamarine;
}
else
{
this.BackColor = System.Drawing.Color.Yellow;
}
}
private void btnOk_Click(object sender, EventArgs e)
{
// you can use _associate object in here since it's an instance field
//Make sure associate has filled in fields
if (this.txtUsername.Text == "" || this.txtPassword.Text == "")
{
MessageBox.Show("You must enter a Username and Password");
return;
}
this.Visible = false;
return ;
}
}

Categories