英文:
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;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论