只允许在文本框中输入数字,并确保第一个数字不是0?

huangapple go评论74阅读模式
英文:

How can I make it so that only numbers can be entered in the TextBox and the first one is not 0?

问题

I need to make it so that only numbers can be entered in the TextBox and so that the first one is not 0. I have a code so that you can enter only numbers, probably it can be improved so that the first digit is not 0.

private void textbox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    if (!Char.IsDigit(e.Text, 0))
    {
        e.Handled = true;
    }
}

I also have a code so that only one ',' can be entered, but I do not know how to redo it for 0.

if (!(Char.IsDigit(e.Text, 0) || (e.Text == ",") && (!TB1.Text.Contains(".") && TB1.Text.Length != 0))){
   e.Handled = true;
}
if ((e.Text == ",") && ((sender as TextBox).Text.IndexOf(',') > -1))
{
   e.Handled = true;
}
英文:

I need to make it so that only numbers can be entered in the TextBox and so that the first one is not 0. I have a code so that you can enter only numbers, probably it can be improved so that the first digit is not 0.

private void textbox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            if (!Char.IsDigit(e.Text, 0))
            {
                e.Handled = true;
            }
        }

I also have a code so that only one ',' can be entered, but I do not know how to redo it for 0.

if (!(Char.IsDigit(e.Text, 0) || (e.Text == ",") && (!TB1.Text.Contains(".") && TB1.Text.Length!=0))){
   e.Handled = true;
}
if ((e.Text == ",") && ((sender as TextBox).Text.IndexOf(',') > -1))
{
   e.Handled = true;
}

答案1

得分: 0

你可以构建新的字符串,然后查询它是否以零开头。

TextBox textBox = (TextBox)sender;
int caretIndex = textBox.CaretIndex;
string newText = textBox.Text.Substring(0, caretIndex) + e.Text + textBox.Text.Substring(caretIndex);
if (newText.StartsWith("0"))
{
    e.Handled = true;
}
英文:

You could compose the new string and then query if it starts with zero

TextBox textBox = (TextBox)sender;
int caretIndex = textBox.CaretIndex;
string newText = textBox.Text.Substring(0, caretIndex) + e.Text + textBox.Text.Substring(caretIndex);
if (newText.StartsWith("0")) 
{
    e.Handled = true;
}

huangapple
  • 本文由 发表于 2023年6月8日 03:12:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76426425.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定