Search code examples
c#integermaskmaxlengthmaskedtextbox

Set a limit on the amount of numbers that can be entered into a "masked textbox"


I am still learning the basics with C# and i am having some trouble. I have been searching the internet for about 3 hours now for an answer on how to set a limit on the amount of characters(in this case it will be limited to a 3 digit integer) a user can enter into a "masked Textbox". I have come across a few different kinds of code, but when i run the program i am still able to enter in as many characters i want. If there is no argument i can add on to do this (meaning i will have to set a loop to check every time) please let me know. I am struggling to learn. Here is the small piece of code that i am attempting to work on.

private void mtbMales_MouseClick(object sender, EventArgs e)
{
    mtbMales.Text = "";
    mtbMales.SelectionStart = 0;
    mtbMales.MaxLength = 3;
    mtbMales.Mask = "000";
}
private void mtbFemales_MouseClick(object sender, EventArgs e)
{

    mtbFemales.Text = "";
    mtbFemales.SelectionStart = 0;
    mtbFemales.MaxLength=3;
    mtbFemales.Mask = "000";
}

Solution

  • Just set the Mask Property of the masked text box to OOO in the design mode, and you're done.

    enter image description here

    If you want to set it programmically, set it in the form load event (Double click the form in Design mode)

    private void Form1_Load(object sender, EventArgs e)
        {
            mtbMales.MaxLength = 3;
            mtbMales.Mask = "000";
        }