如何确保 winform 文本框输入以特定数字开头?



我想确保用户文本框输入以 71 或 72 开头,由 10 位数字组成。否则,将给出错误消息。我该怎么做?

我正在使用Visual Studio 2015。

好吧,你并没有真正告诉我们你尝试过什么或给我们任何限制,所以我将给出一个非常笼统的答案:

public class Program
{
public static void Main(string[] args)
{
string myInput = "";
textBox1.Text.Trim();
if(textBox1.Text.Length() == 10)
{
if(textBox1.Text[0] == '7')
{
if(textBox1.Text[1] == '1' || textBox1.Text[1] == '2')
{
myInput == textBox1.Text();
int num = Int32.Parse(myInput);
//num is now an int that is 10 digits and starts with "71" or "72"
}
}
}
else
{
MessageBox.Show("Invalid input", "Invalid Input");
}          
}
}

此外,您可能可以将所有 if 语句组合成一个大语句。这将允许它与else语句更好地交互。

if ((TextBox.Text().StartsWith("71") || TextBox.Text().StarsWith("72")) && (TextBox.Text().Length == 10))
{
}
else
{

}

正则表达式怎么样:

(71|72)d{8}

基本上,它以 71 或 72 开头,后跟 8 位数字。

如果匹配,此代码将返回布尔值

System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "(71|72)d{8}")

参考:

https://msdn.microsoft.com/en-us/library/sdx2bds0(v=vs.110).aspx

如果你有大量的文本框,那么下面的代码将为你工作。

var boxes = new List<TextBox>
{
textBox1,
textBox2,
textBox3
};
if ((!boxes.Any(x => x.Text.StartsWith("71")) || !boxes.Any(x => x.Text.StartsWith("72"))) && !boxes.Any(x => x.Text.StartsWith("100")))
{
// Code
}
else
{
// Error
}

最新更新