Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何选择文本框的特定部分?_C#_Visual Studio_Textbox - Fatal编程技术网

C# 如何选择文本框的特定部分?

C# 如何选择文本框的特定部分?,c#,visual-studio,textbox,C#,Visual Studio,Textbox,我试图从文本框中挑出特定的字母/数字,因为每一个字母/数字都意味着什么。之后,我试图在标签中显示它的含义 因此,如果我有一个AB-123456号,我需要首先选择AB,比如: If (textBox.Text.Substring(0,2) == "AB") { //Display to a label } 首先,这不起作用,我还尝试了子字符串(0,1),但在使用清除按钮清除文本框时也收到错误 在那之后,我仍然需要提取其余的数字。下一个我需要拉出来定义的是123,然后是4个,5个,还有6个 如

我试图从文本框中挑出特定的字母/数字,因为每一个字母/数字都意味着什么。之后,我试图在标签中显示它的含义

因此,如果我有一个AB-123456号,我需要首先选择AB,比如:

If (textBox.Text.Substring(0,2) == "AB") {

//Display to a label

}
首先,这不起作用,我还尝试了子字符串(0,1),但在使用清除按钮清除文本框时也收到错误

在那之后,我仍然需要提取其余的数字。下一个我需要拉出来定义的是123,然后是4个,5个,还有6个

如果子字符串不起作用,我该如何逐个拉动这些子字符串

string input = textBox.Text;
// check the length before substring 
If (input.Length >= 2 && input.Substring(0,2) == "AB") {
    //Display to a label
}
或使用正则表达式:

string txt="AB-1234562323";
string re="AB-(\\d+)";  // Integer Number 1

 Regex r = new Regex(re,RegexOptions.IgnoreCase|RegexOptions.Singleline);
 Match m = r.Match(txt);
 if (m.Success)// match found
 {
       // get the number 
       String number=m.Groups[1].ToString();  
 }
试试这个:

if (textBox.Text.StartsWith("AB"))
{
    //Display to a label
}

如果不想先检查文本的长度,请使用此选项。此外,如果要忽略大小写,可以包含StringComparison参数。

“不起作用”并不能真正帮助我们。有什么问题吗?我怀疑你得到了一个例外,因为你要求的范围超出了字符串的尺寸?这是一种检查字符串的方法value@Luaan确切地说,它说“索引和长度必须引用字符串中的一个位置。参数名:length”除了“if(textBox.Text.Substring(0,2)=“AB”)”之外,您还做了什么?您的错误只会发生在字符串少于2个字符的情况下。解决方法非常简单-在使用
子字符串之前检查字符串的长度。对于逐字符访问,您只需使用索引器(例如
textBox.Text[7]
)。如果格式是固定的,您还可以使用
MaskedTextBox
进行额外的UI和验证-然后您只能在ID实际有效时尝试解析ID。我使用了第一个ID,它工作正常。但是现在我需要把123从AB-123456上取下来。我将长度重新声明为6,但我不知道如何使用子字符串仅拉出“123”