MaskedTextBox Minimum/Maximum Lengths

若如初见. 提交于 2019-12-13 21:45:24

问题


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;

回答1:


Which approach could be even simpler than what you are suggesting?

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



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/4876323/maskedtextbox-minimum-maximum-lengths

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!