Pregunta

Necesito un cuadro de texto que sólo el usuario puede permitir entrar en números enteros. Pero el usuario no puede entrar en cero. es decir, que puede entrar en 10.100 0 etc. No solo. ¿Cómo puedo hacer en caso KeyDown?

¿Fue útil?

Solución

La forma en que planea hacer esto, es muy molesto para un usuario. Usted está adivinando lo que un usuario quiere entrar y actuar sobre su conjetura, pero puede ser tan malo.

También tiene agujeros, por ejemplo, un usuario puede introducir "10" y luego eliminar el "1". O podría pegar en un "0" -? Que haces permitir que la pasta, ¿no

Así que mi solución sería: vamos a entrar cualquier dígito que le gusta, de cualquier manera que le gusta, y validar la entrada única después terminó, por ejemplo, cuando la entrada pierde el foco

Otros consejos

¿Por qué no usar un NumericUpDown y hacer los ajustes siguientes:

upDown.Minimum = 1;
upDown.Maximum = Decimal.MaxValue;

int.TryParse para convertir el texto en un número y comprobar si ese número no es 0. Use la Validación evento para el registro.

// this goes to you init routine
textBox1.Validating += textBox1_Validating;

// the validation method
private void textBox1_Validating(object sender, CancelEventArgs e)
{
    if (textBox1.Text.Length > 0)
    {
        int result;
        if (int.TryParse(textBox1.Text, out result))
        {
            // number is 0?
            e.Cancel = result == 0;
        }
        else
        {
            // not a number at all
            e.Cancel = true;
        }
    }
}

EDIT:

Está bien, ya que se utiliza WPF usted debe echar un vistazo a cómo implementar la validación del manera WPF. Aquí está una clase de validación que implementa la lógica anterior:

public class StringNotZeroRule : ValidationRule
{
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        if (textBox1.Text.Length == 0)
            return new ValidationResult(true, null);

        int result;
        if (int.TryParse(textBox1.Text, out result))
        {
            // number is 0?
            if (result == 0)
            {
                return new ValidationResult(false, "0 is not allowed");
            }
        }
        else
        {
            // not a number at all
            return new ValidationResult(false, "not a number");
        }

        return new ValidationResult(true, null);
    }
}

Esta es otra variación sobre el tema:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    char newChar = Convert.ToChar(e.KeyValue);
    if (char.IsControl(newChar))
    {
        return;
    }
    int value;
    e.SuppressKeyPress = int.TryParse((sender as TextBox).Text + newChar.ToString(), out value) ? value == 0 : true;
}
    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (textBox1.Text == "" && e.KeyChar == '0')
        {
            e.Handled = true;
            return;
        }
        if (e.KeyChar < '0' || e.KeyChar > '9')
        {
            e.Handled = true;
            return;
        }

    }

No es agradable, pero funciona

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top