I\'m working on a windows forms application (C#) where a user is entering data in a form. At any point while editing the data in the form the user can click one of the butt
Your implementation looks good enough -- what I do want to know is why you want to do this in the first place? Won't it be preferrable for the focus to cycle back to the first entry? Is the data in the last text box so malleable that once they click the button it is "remembered"? Or do you have some sort of operation that the button does to that specifici text box data -- in that case shouldn't the focus go to a subsequent control instead?
I'm interested in finding out why you want to do this in the first place.
Yeah, I admit the requirement is a bit unusual. Some of the information that the users will be entering into this application exists in scans of old documents that are in a couple of different repositories. The buttons facilitate finding and opening these old docs. It's difficult to predict where the users will be on the form when they decide to pull up a document with more information to enter on the form. The intent is to make the UI flow well in spite of these funky circumstances.
Create a class called CustomTextBox that inherits from TextBox. It has a static variable called stack. When the textbox loses focus push onto the stack. When you want to find the last focused control then just pop the first item from the stack. Make sure to clear the static Stack variable.
Your approach looks good. If you want to avoid having to add an the event handler to every control you add, you could create a recursive routine to add a GotFocus listener to every control in your form. This will work for any type of control in your form, however you could adjust it to meet your needs.
private void Form_OnLoad(object obj, EventArgs e)
{
AddGotFocusListener(this);
}
private void AddGotFocusListener(Control ctrl)
{
foreach(Control c in ctrl.Controls)
{
c.GotFocus += new EventHandler(Control_GotFocus);
if(c.Controls.Count > 0)
{
AddGotFocusListener(c);
}
}
}
private void Control_GotFocus(object obj, EventArgs e)
{
// Set focused control here
}
I think what you're doing is fine. The only thing I could think of to improve it would be to store each control into a stack as they are accessed. That would give you a complete time line of what was accessed.
For a bit of 'simplicity' maybe try.
public Form1()
{
InitializeComponent();
foreach (Control ctrl in Controls)
{
if (ctrl is TextBox)
{
ctrl.Enter += delegate(object sender, EventArgs e)
{
_lastEnteredControl = (Control)sender;
};
}
}
}
then you don't have to worry about decorating each textbox manually (or forgetting about one too).