The code builds the list of controls recursively by finding the control and it's parents in parent-child hierarchy. Let's look at a simple code snippet for it:
namespace MyProject.ClientUtility
{
/// <summary>
/// Utility class for forms controls
/// </summary>
public class FormsUtility
{
private List<Control> _focusControlsList = new List<Control>();
public FormsUtility() { }
#region Set Focus to Control
/// <summary>
/// Set focus to a control based on the control name.
/// Pass base(parent) control to loop through all child controls.
/// </summary>
/// <param name="controlName"></param>
/// <param name="baseControl"></param>
/// <returns></returns>
public void SetFocusTo(string controlName, Control baseControl)
{
// Build the control list from parent to child order
BuildControlList(controlName, baseControl);
// Set focus in that order:
foreach (Control eachControl in _focusControlsList)
SetFocus(eachControl);
}
/// <summary>
/// Build the control list from Top-Down
/// </summary>
/// <param name="controlName"></param>
/// <param name="baseControl"></param>
/// <returns></returns>
private bool BuildControlList(string controlName, Control baseControl)
{
if (baseControl.Name == controlName)
{
_focusControlsList.Insert(0, baseControl);
return true;
}
foreach (Control eachControl in baseControl.Controls)
{
if (eachControl.Name == controlName)
{
_focusControlsList.Insert(0, eachControl);
return true;
}
if (eachControl.HasChildren)
{
// recursive...
if (BuildControlList(controlName, eachControl))
{
// going back to each parent to set focus
_focusControlsList.Insert(0, eachControl);
return true;
}
}
}
return false;
}
/// <summary>
/// Focus based on type of control
/// </summary>
/// <param name="controlToFocus"></param>
private void SetFocus(Control controlToFocus)
{
switch (controlToFocus.GetType().ToString())
{
case "System.Windows.Forms.TabPage":
// TabPage must be selected
((TabControl)((TabPage)controlToFocus).Parent).SelectedTab =
(TabPage)controlToFocus;
break;
default:
controlToFocus.Focus();
break;
}
}
#endregion
}
}
Love coding!
No comments:
Post a Comment