質問
いテキストボックスだけをユーザが入の整数です。そのユーザーが入っゼロになります。ん。e、入10,100。0でない。かのイベント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;
}
}
}
編集:
大丈夫、以降のご利用のコンポーネントのラインナップするべきかを 検証は、コンポーネントのラインナップ方法.ここで検証を実装するクラス上の論理:
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