Auto set minimum and maximum value on textbox

2020-07-13 09:48发布

问题:

I want to make the textbox automatically set the maximum value when the user put the value above the maximum value. Example min is 0 and max is 255. When user put 999 in the textbox, it automatically set to 255 as the max value. When user put -11 on textbox, it automatically set to 0 as the min value. You can see the gif animation below how it should work

I had tried if else statement but it could not convert string to int.

回答1:

you should set this on every text box you want this functionality for.

it simply check for Text of the textbox if it is numerical then it checks for ranges and apply appropriate value

yourtextbox.TextChanged+= (s, e) =>
{
    var textbox = s as TextBox;
    int value;
    if (int.TryParse(textbox.Text, out value))
    {
        if (value > 255)
            textbox.Text = "255";
        else if (value < 0)
            textbox.Text = "0";
    }
}


回答2:

Use the textbox's ontextchange event In the event check:

if (int.Parse(textBox.Text) > MAX_VALUE) {
    textBox.Text = MAX_VALUE;
}