Well i had a situation where i need to reset all controls (mostly Textboxes and Comboboxes) on form to their default (entry ready) state. Well, at first sight I was thinking it’s not a problem, my .net Win form have property called Controls – list of all controls on form. But problem was that i had overlapping panels which i used for positioning, and inside of panels was Group box control. So it’s allready complicated then at first sight.
I have created little Form helper which will help you reset all controls on form to their default state.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace UI.Forms
{
public class FormHelper
{
public static void ResetFields(Control form)
{
foreach (Control ctrl in form.Controls)
{
if (ctrl.Controls.Count > 0)
ResetFields(ctrl);
Reset(ctrl);
}
}
public static void Reset(Control ctrl)
{
if (ctrl is TextBox)
{
TextBox tb = (TextBox)ctrl;
if (tb != null)
{
tb.ResetText();
}
}
else if (ctrl is ComboBox)
{
ComboBox dd = (ComboBox)ctrl;
if (dd != null)
{
dd.SelectedIndex = 0;
}
}
}
}
}
Sample usage – calling method from code behind form:
Example:
FormHelper.ResetFields(this);
Where this is reference to Form on which controls resides
I hope you’ll find it useful.
actualy, you can add a “Settigs” file to your project, bind your control properties to settings variables and then save it or reset it…
for exemple:
MySettings.Default.Save();
or
MySettings.Default.Reset();
In first case all binded properties will be saved to the next opening of your application.
In the second case all your control properties will be reset to default value.
Hi Tone,
Thanks for your suggestion and it is nice idea if you want to do more with state of your controls, but i needed quick way to just reset all controls on form without any setup
nice post