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;
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 notEnabledthen you won’t be able to set focus.Check the
CanFocusproperty 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’sGotFocusevent 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? GenerallyTabIndexis 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.