I want to bring the cursor to a textbox when i clicked a button. How can i do that? I tried Focus() method but it didn't not work. The code is shown below.
CsNIPAddrTextBox.Focus();
CsNIPAddrTextBox.TabIndex = 1;
To position the cursor at the beginning of the contents of a TextBox control, call the Select method and specify the selection start position of 0, and a selection length of 0.
SetCursorPosition(Int32, Int32) Method is used to set the position of cursor. Basically, it specifies where the next write operation will begin in the console window.
Try textbox1.select()
. It's the best approach to bring your cursor to your textbox. It also selects content of the texbox which makes it easier for the user to edit what's inside the textbox.
If that's a 'proper' TextBox (i.e. not custom) then simply calling Focus()
should work. It might not, however, if it's read-only (I'm not sure - I've not tried. I know you can get a caret in a read-only box, which implies it can get focus). Certainly if it's not Enabled
then you won't be able to set focus.
Check the CanFocus
property is true - if it's not, then there might be some other reason preventing the control from receiving focus.
If that's true
, however, and the caret still doesn't make it to the control - you need to verify that it is receiving it. Add an event handler for the text box's GotFocus
event and breakpoint it to clarify that it gets hit. My guess is that it your breakpoint will be hit. If so - then the answer is that another process is setting focus to another control immediately after your button click occurs. For example, if you do this kind of thing in a validation event handler you'll get a similar result, because the Windows Forms pipeline is already in the process of changing controls when the handler is fired.
Also - why are you setting TabIndex=1
? Generally TabIndex
is set at design time and left alone (unless of course these are dynamically created). Unless you have a particular reason for doing this I'd get rid of that line. It doesn't have a bearing on why this would/wouldn't work - just an observation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With