winforms 在掩码文本框中使用变量

l3zydbqr  于 8个月前  发布在  其他
关注(0)|答案(1)|浏览(60)

我想制作一个格式为xxxx/##/##的屏蔽文本
xxxx是一个存储在配置变量中的数字,应该在“表单加载”中加载,我该怎么办?
另外,当我将mask设置为1402/##/##时,它变为14_2/__ /__
第1402章我想静一静
抱歉我的英语

zaqlnxep

zaqlnxep1#

您需要使用反斜杠转义掩码静态部分中的每个字符。参见文档中的备注。
\转义掩码字符,将其转换为文本。“\”是反斜杠的转义序列。
在这种情况下,掩码将如下所示:

maskedTextBox1.Mask = @"\1\4\0\2/00/00";

可以通过编程方式转义字符。假设您有以下配置文件,其中包含掩码的静态部分。

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
        <add key="number" value="1402"/>
    </appSettings>
</configuration>

然后可以按如下方式转义字符:

using System.Configuration;
using System.Text;
using System.Windows.Forms;

namespace Test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            // Initialize the masked text box.
            var maskedTextBox1 = new MaskedTextBox
            {
                Location = new System.Drawing.Point(10, 10)
            };
            Controls.Add(maskedTextBox1);

            // Read the static number from the configuration file.
            var number = int.Parse(ConfigurationManager.AppSettings["number"]);
            
            // Split the number into individual characters and escape them.
            var prefix = new StringBuilder();
            foreach (var character in number.ToString())
            {
                prefix.Append(@"\");
                prefix.Append(character);
            }

            // Set the updated mask.
            maskedTextBox1.Mask = prefix + "/00/00";
        }
    }
}

相关问题