如何从 TextBox 获取值并自动应用格式? [英] How to get values from a TextBox and apply a format automatically?
问题描述
下面是我的占位符,其中的值是硬编码的:
Below is my place holder in which the values are hard-coded:
var abc = string.Format($"{123456} {123456} {12345} {123456789012345} {12345678901234567890123} {1234} {1234} {123} {1234567890123} {123456789012345} {1} {123456789012345}
{123} {12} {12345678901234567890} {1} {1234}");
File.WriteAllText(
FilePath + "\\CDR-" +
DateTime.Now.ToString("MM-dd-yyyy HH-mm-ss") + ".txt", abc);
但我想在这些占位符中自动从 TextBox 获取值.
But I want to get values from the TextBox automatically in these placeholders.
假设下面是我的 TextBox 及其值:
Suppose below is my TextBox and its value:
123456 123456 12345 123456789012345 12345678901234567890123
1234 1234 123 1234567890123 123456789012345 1 123456789012345
123 12 12345678901234567890 1 1234
推荐答案
可以使用序列分隔符来分割输入字符串(这里好像是一个空格),使用string.Spilt() 作为 字符串的输入.Format()
方法.
You can split the input string using the sequence separator (it appears to be a white space here), and use the string array generated by string.Spilt() as the input of the string.Format()
method.
像这样:
string filePath = @"[Some Path]";
string[] values = textBox1.Text.Split();
var format = string.Format(
"{0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {10} {11} {12} {13} {14} {15} {16}",
values);
File.WriteAllText(Path.Combine(filePath,
"CDR-" + DateTime.Now.ToString("MM-dd-yyyy HH-mm-ss") + ".txt"),
format);
如果您有不同的分隔符,请将其指定为 Split()
方法的参数.
If you have a different separator, specify it as a parameter of the Split()
method.
空格是预定义的字符.在这种情况下不需要指定它.使用不同的符号:
The white space is the predefined character. No need to specify it in this case. With different symbols:
- 单个字符:
[someString].Split(',');
- 不止一个:
[someString].Split(new[] {',', '+'});
- 字符串:
[someString].Split(new[] { ",", "+" }, StringSplitOptions.RemoveEmptyEntries);
这篇关于如何从 TextBox 获取值并自动应用格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!