Use variable in masked textbox

65 Views Asked by At

I want to make a masked text with this format xxxx/##/##

the xxxx is a number stored in a variable in config and should load on "form load" what should I do ?

Also when I set mask to 1402/##/## , it become 14_2/__ /__

but I want to 1402 be static !

sorry for my English

1

There are 1 best solutions below

3
Sergey On BEST ANSWER

You need to escape each character in the static part of your mask using backslash. See remarks in the documentation.

\ Escapes a mask character, turning it into a literal. "\" is the escape sequence for a backslash.

In you case, the mask will look as follows:

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

You can escape the characters programmatically. Imagine you have the following configuration file that includes the static part of the mask.

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

Then you can escape the characters as follows:

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

enter image description here