Setting Focus on a Field Dynamically?

BlakeMcKenna

Active member
Joined
Oct 27, 2008
Messages
38
Programming Experience
10+
I have a form in which a number of different controls are created dynamically. They are primarily TextBoxes and ComboBoxes. As I create these controls dynamically, I count them as they are created. Therefore, I set the TabIndex of each control to the corresponding count. My question is...how can I set the focus to the next field according to the count when I might not know what kind of control is the next field?

I hope I explained this correctly.

Thanks,
 
All controls derive from Control class, which has the Select method you want to use. There is also the GetNextControl method that returns the next control in tab order. Here is an example that selects next control in tab order after a "Button1":
VB.NET:
Me.GetNextControl(Button1, True).Select()
Which event are you targeting when moving to next control?
 
John,

I would be setting the focus in the Leave() Event...I see that your using "Button1"...what is this reference exactly. I'm thinking it's the current control that has the focus...
 
John,

I would be setting the focus in the Leave() Event...I see that your using "Button1"...what is this reference exactly. I'm thinking it's the current control that has the focus...
Button1 would be the button on John's form that's named Button1

You'd need to change 'Button1' to the name of your control
 
That's the issue...I don't know what the next control will be.
But you know what the current control is, which is all you need. Button1 in John's code is the current control and it's that control that the code needs to move to the next one in the tab order.
 
I see what your saying. In that case, this might be a viable option. Just need to see how much time it will take.

By putting this in the Enter event you're able to determine what the next control will be in the tab order. Obviously you've got a better purpose in mind than displaying a MessageBox :)

VB.NET:
		Dim nextControl As Control = Me.GetNextControl(ActiveControl, True)

		MessageBox.Show(String.Format("Current Control: {0}{1}{0}{2}{0}Next Control:{0}{3}{0}{4}", _
		 Environment.NewLine, _
		 ActiveControl.GetType(), _
		 ActiveControl.Name, _
		 nextControl.GetType(), _
		 nextControl.Name))
 
In the Leave event why not just do this:
VB.NET:
Me.GetNextControl(Sender, True).Select()
? That's assuming that getNextControl accepts an object as an argument.
 
Back
Top