如何将值拆分为2个值

时间:2012-10-14 09:09:44

标签: c# vb.net

像这样的用户输入

textbox1.text = 01/02/03/......

我想在3个文本框中分别显示这些值

"/"之后,它应移至下一行

txt1.text =  01
    txt2.text = 02
   txt3.text =  03
    ....

如何做到这一点。

需要Vb.net代码帮助

3 个答案:

答案 0 :(得分:3)

选项1

如果它总是3个文本框,你可以为每个文本框编写静态代码,如下所示:

'EDIT: This code now checks for the existence of a second or third value to avoid
'out of bounds errors
Dim originalValue As String = "01/02/03"
Dim splitBySlash As String() = originalValue.Split("/")

txt1.Text = splitBySlash(0)
If splitBySlash.Length > 1 Then txt2.Text = splitBySlash(1)
If splitBySlash.Length > 2 Then txt3.Text = splitBySlash(2)

选项2

如果您有基于斜杠的可变数量的文本框,则必须在运行时创建它们并将它们添加到父控件,如下所示:

'You can enter as many (or few) slashes as you like in this code, it will automatically
'adjust the text boxes created as necessary.
Dim originalValue As String = "01/02/03" 'could go on like /04/05/etc
Dim splitBySlash As String() = originalValue.Split("/")

For Each value As String In splitBySlash
    Dim newTxt As New TextBox()
    newTxt.Text = value

    yourParentControl.Controls.Add(newTxt)
Next

答案 1 :(得分:1)

试试这个:

string rockString =  "01/02/03/";
string[] words = rockString.Split('/');
foreach (string word in words)
    {
      Console.WriteLine(word);
     }

正如您在评论中所提出的

在不同的文本框中

textbox1.text = words[0]; //textbox1.text="01";
    textbox2.text = words[2]; //textbox2.text="02";
    textbox3.text = words[3]; //textbox3.text="03";

在同一文本框中

 textbox1.text = words[0]+words[1]+words[2];

答案 2 :(得分:0)

尝试使用String.Split或Regex.Split

Dim value As String = "01//02//03//" 
Dim lines As String() = Regex.Split(value, "//") 
For Each line As String In lines    
Console.WriteLine(line) 
Next