C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Info: TextFocusedFirstLoop loops through every Control in the this.Controls collection on the Form. Every Control is checked to see if it is focused.
ForeachCast: The as-operator tries to cast an object to another type. We try to cast to the TextBox type. If the object cannot be cast, it is set to null.
Finally: The TextBox is returned. If the focused control is a TextBox, it returns it. If nothing matches, it returns null.
AsNullImplementation 1: C#
private TextBox TextFocusedFirstLoop()
{
// Look through all the controls on this form.
foreach (Control con in this.Controls)
{
// Every control has a Focused property.
if (con.Focused == true)
{
// Try to cast the control to a TextBox.
TextBox textBox = con as TextBox;
if (textBox != null)
{
return textBox; // We have a TextBox that has focus.
}
}
}
return null; // No suitable TextBox was found.
}
private void SolutionExampleLoop()
{
TextBox textBox = TextFocusedFirstLoop();
if (textBox != null)
{
// We have the focused TextBox.
// ... We can modify or check parts of it.
}
}
Also: It is simpler to understand and shorter. But it must be carefully maintained.
Here: In this example, each TextBox control is separately tested. This method must be updated for each program and each new TextBox added.
Note: There is no loop in TextFocusedFirst so it avoids iterating over controls that are not TextBox objects.
Implementation 2: C#
private TextBox TextFocusedFirst()
{
// mainBox2 is a TextBox control.
if (mainBox2.Focused == true)
{
return mainBox2;
}
// titleBox2 is a TextBox control.
if (titleBox2.Focused == true)
{
return titleBox2;
}
// passwordTextBox is a TextBox control.
if (passwordTextBox.Focused == true)
{
return passwordTextBox;
}
return null; // Nothing is focused, so return null.
}
private void SolutionExample()
{
TextBox textBox = TextFocusedFirst();
if (textBox != null)
{
// We have the focused TextBox.
// ... We can modify or check parts of it.
}
}
Loop method
10218
18431
35621
21423 [Average]
Manual check method
7653
15358
22653
15221 [Average]