Checking if user inputed a valid number in Text Box

时间:2019-04-17 00:45:59

标签: c# wpf

I'm trying to have it so when a user enters a number below zero or a string, the textbox background changes to red. If they enter a number greater or equal to 0 then the text box stays the same white color. It will be red until the user enters a correct integer. I also want the number to be stored in a variable. I wrote the code below, but it is a mix of code I've using in cmd programs, so not sure how it is done in WPF.

 _heightVal = 0;

private void TxtFeetInput_TextChanged(object sender, TextChangedEventArgs e)
        {

            _heightVal = double.Parse(txtFeetInput.Text);

            if (heightVal = "")/*any string*/
            {
                textBox1.Background = Brushes.Red;
            }
            else if (_heightVal < 0)
            {
                textBox1.Background = Brushes.Red;
            }
            else
            {
                textBox1.Background = Brushes.White;
            }
        }

2 个答案:

答案 0 :(得分:1)

Try the following:

double i = 0;  
string s = txtFeetInput.Text;
bool result = double.TryParse(s, out i);

if(result && i >= 0){
    textBox1.Background = Brushes.White;
}else{
    textBox1.Background = Brushes.Red;
}

答案 1 :(得分:0)

您可以使用以下内容。

 private void TxtFeetInput_TextChanged(object sender, TextChangedEventArgs e)
 {
    if (string.IsNullOrEmpty(txtFeetInput.Text))
    {
       textBox1.Background = Brushes.White;
       return;
    }
    textBox1.Background = double.TryParse(txtFeetInput.Text, out var value) 
                                     && value >= 0? 
                                     Brushes.White : Brushes.Red;
 }