【问题标题】:Is there a easier way to format this string?有没有更简单的方法来格式化这个字符串?
【发布时间】:2021-06-08 01:45:48
【问题描述】:

我一直在尝试将这个字符串格式化为一个文本框,因为它正在被输入。我想要的输出结果如下:

用户按下'0':输出:'0 //'

用户按下'6':输出:'06//'

用户按下'2':输出:'06/2 / '

等等

我目前拥有的:

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;
    }
}

有什么方法可以让这更精简吗?我尝试了其他一些想法,但这是唯一可行的。

【问题讨论】:

  • 看看MaskedTextBox
  • ...或者更好,DateTimePicker。您可以将其 Format 属性设置为 Short 或将其设置为 Custom 并使用自定义格式。如果您不希望用户从日历中进行选择,也可以将 ShowUpDown 设置为 true。

标签: c#


【解决方案1】:

您可以将MaskedTextbox 与输入掩码00/00/0000 一起使用。

编辑你也可以将ValidatingType属性设置为DateTime类型。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2011-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
  • 2018-03-30
  • 1970-01-01
相关资源
最近更新 更多