user3763113
user3763113

Reputation:

Auto set minimum and maximum value on textbox

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

https://i.sstatic.net/93Tqg.gif

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

Upvotes: 5

Views: 19307

Answers (2)

Hamid Pourjam
Hamid Pourjam

Reputation: 20754

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";
    }
}

Upvotes: 4

Matansh
Matansh

Reputation: 782

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

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

Upvotes: 3

Related Questions