Wednesday 5 December 2012

How to Clear the All the controls in a form in c#.net in Realtime

In every project we have to Clear the controls which is nothing but NEW button,in our project whenever
we press the NEW button for new form it clear the all the controls in current form.For that we I gave
class(DLL)file with code using this DLL Clear all the controls in your form even the controls are inside the TAB Control or SplitContainer or etc shown below.
Code:

    public  void ClearFields(Control cntr)
        {
            foreach (Control ct in cntr.Controls)
            {             
                if (ct is TextBox)
                {
                    ((TextBox)ct).Clear();
                }
                else if (ct.HasChildren)
                {
                    ClearFields(ct);
                }
                else if (ct is ComboBox)
                {
                    ((ComboBox)ct).SelectedIndex = -1;
                }
                else if (ct is RichTextBox)
                {
                    ((RichTextBox)ct).Clear();
                }
                else if (ct is DataGridView)
                {
                    ((DataGridView)ct).Rows.Clear();
                }
            }
        }

Creat the class with this code and invoke into your application and call the method in your NEW button.
I hope this code willl help you.