Search code examples
c#dynamictextbox

Validate input to a simple textbox depending on chosen type


I am doing some preparation for my fresher year and I kind of got myself into a mess which I am unable to solve. If you look at the picture below:

This picture

You can see that I have a text box which I cannot figure out how to make it to accept only certain characters such as 0-7 sans 8 and 9 for octal for example.

Here is my code so far:

private void inputBox_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (hexRadioButton.Checked)
        {
            if (char.IsWhiteSpace(e.KeyChar))
            {
                e.Handled = true;
            }
        }
        if (decimalRadioButton.Checked)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) ||  char.IsWhiteSpace(e.KeyChar))
            {                    
                e.Handled = true;
            }
        }

        if (octalRadioButton.Checked)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) ||  char.IsWhiteSpace(e.KeyChar))
            { 
                e.Handled = true;
            }
            e.Handled = false;
        }

        if (radioButton1.Checked)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) || char.IsWhiteSpace(e.KeyChar))
            {
                e.Handled = true;
            }
            e.Handled = false;
        }
    }

I also have tried to do something like this:

if (octalRadioButton.Checked)
            {
                if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) ||  char.IsWhiteSpace(e.KeyChar) || char.IsDigit('7') || char.IsDigit('8'))

but that did barely anything.


Solution

  • I think the big problem is here:

    if (octalRadioButton.Checked)
    {
        if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) ||  char.IsWhiteSpace(e.KeyChar))
        { 
            e.Handled = true;
        }
        e.Handled = false; <----------
    }
    

    After you set it to true, you set it to false again... So that's why it allows you to enter invalid chars.

    So remove that line.

    The second problem is that you are accepting all digits, including 8 and 9. To fix this, I would do something like this:

    var validChars = new[] {'1', '2', '3', '4', '5', '6', '7'};
    if (!validChars.Contains(e.KeyChar)) {
        e.Handled = true;
    }
    

    You can use this approach for other bases as well.

    Edit:

    Actually, I just looked at the docs, and Handled apparently won't work. You need the SuppressKeyPress property, and set that to true in the KeyDown event.