I'm trying to create a method to simply clear all textboxes in a webform.
This is the code I'm calling:
private void clearFrom()
{
IEnumerable<TextBox> textBoxes = Controls.OfType<TextBox>();
foreach (TextBox textBox in textBoxes)
{
textBox.Text = string.Empty;
}
}
It doesn't error, just never gets to call textBox.Text = string.Empty;
I'm guessing the list of textboxes has not been created and suspect I'm missing an important step. I reckon there is something wrong with Controls.OfType<TextBox>()
I also tried using the following:
private void clearFrom()
{
IEnumerable<TextBox> Textboxes = (from Control c in this.Controls
where c.GetType() == typeof(TextBox)
select c).AsEnumerable().Cast<TextBox>();
FunctionalExtensions.ForEach(Textboxes, ClearTextBox);
}
public static class FunctionalExtensions
{
public static void ForEach<T>(IEnumerable<T> items, Action<T> DoSomething)
{
foreach (T item in items)
{
DoSomething(item);
}
}
}
private void ClearTextBox(TextBox txtbox)
{
txtbox.Text = string.Empty;
}
Again it didn't error but never called ClearTextBox
.
I know it's a c# schoolboy error and to be honest the penny hasn't dropped as to what IEnumerable
is actually doing. Any help would be appreciated.