MaskedTextBox Minimum/Maximum Lengths

2019-09-06 22:44发布

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;

3条回答
做个烂人
2楼-- · 2019-09-06 23:05

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楼-- · 2019-09-06 23:12

// 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;
    }
查看更多
贪生不怕死
4楼-- · 2019-09-06 23:23

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

myTextBox.Textchanged+=(s,o)=>{ myButton.Enabled = myTextBox.Length==10; };
查看更多
登录 后发表回答