Избегайте пробелов и отображайте сообщение об ошибке в текстовом поле, используя c# visual studio - PullRequest
0 голосов
/ 03 апреля 2020

У меня есть TextBox и кнопка сохранения. Textbox установлен только для цифр, должен содержать не менее 3 цифр и не более 4 цифр. Мне нужно сделать так, чтобы при вводе всего или даже одного пробела в поле мне отображалось сообщение об ошибке. В текущем коде я установил сообщение об ошибке, которое будет отображаться при вводе 2 цифр. Но mtuValue является свойством int. Мне нужно заявление if, чтобы избежать и отобразить whitespace. Код такой, как показано ниже. Это текущий код для любого набора на данный момент. Итак, все, что мне нужно, это оператор if для whitespace. Большое спасибо заранее.

private ICommand MTUsavecommand_;
public ICommand MTUsavecommand
{
    get
    {
        if (null == MTUsavecommand_)
        {
            MTUsavecommand_ = new RelayCommand(o =>
            {
                if (mtuValue < 100)
                {
                    MtuMsg = "MTU value should be atleast 3 digits.";
                    MtuMsgVisibility = Visibility.Visible;
                }
                else
                {
                    Mouse.OverrideCursor = Cursors.Wait;
                    RouteManager?.DoMTU();
                    Mouse.OverrideCursor = null;
                    MtuMsg = "MTU saved successfully. Service will be restarted.";
                    MtuMsgVisibility = Visibility.Visible;
                }
            });
        }
        return MTUsavecommand_;
    }
}

public int mtuValue
{
    get { return Configuration.MTU; }
    set
    {
        if (Configuration.MTU != value)
        {
            Configuration.MTU = value;
            OnPropertyChanged();
        }
    }
}

1 Ответ

0 голосов
/ 06 апреля 2020

Если ваш проект 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");
    }
}
...