[英]Is there a easier way to format this string?
I've been attempting to format this string for a text box as it's getting typed in. The output result that I would like is as follows:我一直在尝试将这个字符串格式化为一个文本框,因为它正在被输入。我想要的 output 结果如下:
user presses '0' : output:'0 / / '用户按'0' :output:'0 //'
user presses '6' : output:'06/ / '用户按'6' :output:'06//'
user presses '2' : output:'06/2 / '用户按下'2' :output:'06/2 /'
etc.等等
What I currently have:我目前拥有的:
private void fTranDate_KeyPress(object sender, KeyPressEventArgs e)
{
if(!Char.IsNumber(e.KeyChar) && !Char.IsControl(e.KeyChar) && fTranDate.Text.Length > 10)
{
e.Handled = true;
}
else if (!Char.IsControl(e.KeyChar)) //Is numeric
{
//Get the string from the field
var existing_string = fTranDate.Text;
//Strip the spaces and the slashes from the string
existing_string = existing_string.Replace("/", "").Replace(" ","");
//Append the new digit to the end of the string
existing_string= existing_string + e.KeyChar;
//Re-add the spaces on the end of the string
existing_string = String.Format("{0,-8}", existing_string);
var existing_char = existing_string.ToCharArray();
fTranDate.Text = String.Format("{0}{1}/{2}{3}/{4}{5}{6}{7}", existing_char[0],existing_char[1],existing_char[2],existing_char[3],existing_char[4],existing_char[5],existing_char[6],existing_char[7]);
fTranDate.SelectionStart = fTranDate.Text.Replace(" ","").Length;
fTranDate.SelectionLength = 0;
e.Handled = true;
}
}
Is there any way to make this more streamlined?有什么办法可以让这更精简吗? I've tried some other ideas but this is the only one that works.
我尝试了其他一些想法,但这是唯一可行的想法。
You can use the MaskedTextbox with the input mask 00/00/0000
.您可以将MaskedTextbox与输入掩码
00/00/0000
使用。
Edit you can also set the ValidatingType
property to DateTime
type.编辑您还可以将
ValidatingType
属性设置为DateTime
类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.