Click here to Skip to main content
15,914,608 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My Code:
C#
private void txtCategoryCode_TextChanged(object sender, EventArgs e)
        {
            
            txtCategoryCode.KeyPress += new KeyPressEventHandler(MyKeyPress);
        }

        void MyKeyPress(object sender, KeyPressEventArgs e)
        {
            TextBox txt = sender as TextBox;
            if (txt.Text.Length > 3)
            {
                e.Handled = true;
                MessageBox.Show("Category Code should be in 3 letters.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


This code is not working. Please tell me where I have to change in my code to do work?
Posted
Comments
[no name] 15-Aug-12 15:35pm    
Are you sure that you want to add an event handler each time the text changes in the textbox?

Event handlers should not be called explicitly. They are called when ever the event is raised.

You just need to set the MaxLength property for the textbox at design time and it will work.
 
Share this answer
 
Try this:-
first write the code in txtCategoryCode Key press event and in txtCategoryCode textChenged event write the following code:-
C#
this.txtCategoryCode.Keypress +=new EventHandler(txtCategoryCode_KeyPress);
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900