TextBox에서 0을 허용하지 않습니다
-
21-08-2019 - |
문제
사용자 만 정수를 입력 할 수있는 텍스트 상자가 필요합니다. 그러나 사용자는 0을 입력 할 수 없습니다. 즉, 그는 0이 아닌 10,100 등을 입력 할 수 있습니다. KeyDown에서 이벤트를 어떻게 만들 수 있습니까?
해결책
이를 계획하는 방식은 사용자에게 매우 성가시다. 당신은 사용자가 입력하고 싶어하는 것을 추측하고 추측에 따라 행동하지만, 당신은 너무 잘못 될 수 있습니다.
예를 들어, 구멍이 있는데, 사용자는 "10"을 입력 한 다음 "1"을 삭제할 수 있습니다. 아니면 "0"에 붙여 넣을 수 있습니다. 페이스트를 허용하지 않습니까?
그래서 내 해결책은 다음과 같습니다. 그가 좋아하는 모든 숫자, 그가 좋아하는 방식으로 입력하고 입력 만 입력하십시오. ~ 후에 예를 들어 입력이 초점을 잃었을 때 그는 끝났습니다.
다른 팁
NumericUpdown을 사용하고 다음 설정을하지 않겠습니까?
upDown.Minimum = 1;
upDown.Maximum = Decimal.MaxValue;
사용 int.tryparse 텍스트를 숫자로 변환하고 해당 숫자가 0이 아닌지 확인하려면 검증 수표 이벤트.
// 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;
}
}
}
편집하다:
좋아, WPF를 사용하므로 구현 방법을 살펴 봐야합니다. 검증 WPF 방식. 다음은 위의 논리를 구현하는 검증 클래스입니다.
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);
}
}
이것은 테마의 또 다른 변형입니다.
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;
}
}
좋지는 않지만 작동합니다
제휴하지 않습니다 StackOverflow