Hello,
I have two textboxes txt1 and txt2. I have set the maxlength of the txt1 to 5. When it reaches the maxlength it shifts the focus to txt2. The problem is on keypress event when I come back and make some corrections it shifts focus to the next textbox which I do not want to happen.
Eg: I have "BRAIN" in txt1 and when I come back and wanted it to change to BRIAN. it is not letting me to change the entire text instead when I press any key it shifts focus to the next textbox even when I select the text by mouse and keyboard. I want to make the necessary changes and when I reach the limit of maxlength I want the focus to be shifted. How to overcome this problem?

Sam HobbsRank #107 · 20.5K reputationPosted Nov 16, 2023, 3:56 PM EST
If txt1 has BRAIN then can you delete a character first and then add a character? If that works and you need something else to happen then you will need to write code to do what you need instead of using maxlength.
kemli zurdo14 reputationPosted Nov 16, 2023, 4:05 PM EST
I can select the first character but when I press any key it shifts the focus to the next textbox.
Amit MohantyRank #112 · 20K reputationPosted Nov 17, 2023, 12:49 AM EST
You can use
txt1_KeyDownevent prevents moving the focus totxt2on keypress if the maximum length is already reached, except when the pressed key is the "Backspace" key (Keys.Back). For example:public partial class Form1 : Form { public Form1() { InitializeComponent(); txt1.MaxLength = 5; } private void txt1_TextChanged(object sender, EventArgs e) { if (txt1.Text.Length >= txt1.MaxLength) { txt2.Focus(); } } private void txt1_KeyDown(object sender, KeyEventArgs e) { if (txt1.Text.Length >= txt1.MaxLength && e.KeyCode != Keys.Back) { e.SuppressKeyPress = true; } } }Rajanikant HawaldarRank #110 · 20.2K reputationPosted Nov 19, 2023, 10:59 AM EST
Use flag to achieve it,