简体   繁体   中英

MaskedTextBox Minimum/Maximum Lengths

I have a masked textbox with the need to have a min/max length set on them. When these conditions are met a button becomes enabled.

I was thinking of handling the TextChanged event to determine the length of the entered text and set the buttons enabled value.

Is there a better approach?

 btnOK.Enabled = txtDataEntry.Text.Length >= MinDataLength && txtDataEntry.Text.Length <= MaxDataLength;

// At your texbox valdating Event

    private void textBox4_Validating(object sender, CancelEventArgs e)
    {
        TextBox tb = sender as TextBox;
        if (tb != null)
        {
            int i=tb.Text.Length;
            //Set your desired minimumlength here '7'
            if (i<7)
            {

                MessageBox.Show("Too short Password");
                return;

            }
        }
        else

        e.Cancel = true;
    }

IMO TextChanged event is good place to handle this feature condition.

Update

Do it in KeyPress event like this:

maskedtxtbox.KeyPress => (s , ev ) { 
                    if(maskedtxtbox.Length > 9)
                    {
                       //This prevent from key to go to control
                       e.Handled =true;
                       button1.Enabled = true;
                    } 
                 };

哪种方法甚至比您建议的简单?

myTextBox.Textchanged+=(s,o)=>{ myButton.Enabled = myTextBox.Length==10; };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM