格式化文本框(电话号码,手机号码,电子邮件)

时间:2016-10-05 15:57:33

标签: c# textbox format string-formatting

我想知道如何将文本框输入转换为不同的格式。我尝试使用Format.String(),因为它是'解决方案'我做了一些研究之后在网上找到了,但对我来说并不好。

  private void RegHomePhoneTBox_TextChanged(object sender, EventArgs e)
    {
        string s = RegHomePhoneTBox.Text;
        double sAsD = double.Parse(s);
        RegHomePhoneTBox.Text = string.Format("{0:###-####}", sAsD).ToString();
    }

这是我使用的代码块,它只是继续抛出错误。

  

未处理的类型' System.FormatException'发生在   mscorlib.dll其他信息:输入字符串不正确   格式。

2 个答案:

答案 0 :(得分:0)

我建议您使用MaskedTextBox。它的工作方式与常规文本框相似,但用户必须以特定格式输入文本。

在您的具体情况下,只需将Mask属性设置为"000-0000"

这是文档:

https://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.mask(v=vs.110).aspx

MaskedTextBox中有很多其他属性非常有用,例如MaskCompleted

答案 1 :(得分:0)

试试这个:

  private void RegHomePhoneTBox_TextChanged(object sender, EventArgs e)
    {
        string s = RegHomePhoneTBox.Text;
        if (s.Length == 7)
        {
           double sAsD = double.Parse(s);
           RegHomePhoneTBox.Text = string.Format("{0:###-####}", sAsD).ToString();
        }
        if (RegHomePhoneTBox.Text.Length > 1)
             RegHomePhoneTBox.SelectionStart = RegHomePhoneTBox.Text.Length;
        RegHomePhoneTBox.SelectionLength = 0;
    }
相关问题