Если ваш проект Winforms
, вы можете проверить, соответствуют ли числа в TextBox требованиям через событие TextChanged
. И вы можете использовать элемент управления errorProvider , чтобы показать подсказки об ошибках.
public Form1()
{
InitializeComponent();
// Set the blinking style: The error icon has been displayed, and blinks when it is still wrong to assign a new value to the control.
errorProvider.BlinkStyle = ErrorBlinkStyle.BlinkIfDifferentError;
// Set the distance of the error icon from the control
errorProvider.SetIconPadding(this.textBox, 5);
}
private void textBox_TextChanged(object sender, EventArgs e)
{
// Use TryParse method to check the format of digit (a properly formatted number should not contain spaces)
int number;
bool success = Int32.TryParse(textBox.Text, out number);
string temp = textBox.Text.Trim();
if (success && temp.Length == textBox.Text.Length) // Check for spaces at the beginning and end
{
// Check the number of digits
if (textBox.Text.Length < 3 || textBox.Text.Length > 4)
errorProvider.SetError(this.textBox, "Please input 3 or 4 digits");
else
errorProvider.SetError(this.textBox, "");
}
else // Wrong format
{
errorProvider.SetError(this.textBox, "Please input digit in right format");
}
}