Wednesday, January 28, 2009

Clearing all textbox and combobox in C#

The "foreach" statement repeats a group of embedded statements for each element in an array or an object collection .The "foreach" statement is used to iterate through the collection to get the information that you want, but can not be used to add or remove items from the source collection to avoid unpredictable side effects. For example we can loop through the controls with in a form or containers(eg: Panels,groupboxes etc).

in the below example we loop through all the controls in a groupbox and check whether it contains any textbox or combobox.If found then we clear its contents.

foreach (Control ctrl in groupBox2.Controls) //loop through controls in the groupbox
{
if (ctrl is TextBox)//checking whether the control is a textbox(Textbox is a class).
{
(ctrl as TextBox).Clear();
}
else
if(ctrl is ComboBox)//checking whether the control is a ComboBox(ComboBox is a class).
{
(ctrl as ComboBox).Text = "";
}
}

Simple isn't it.

1 comment:

  1. combo box is not cleared
    public void clrcombo(Control.ControlCollection cl)
    {
    foreach (Control ctr in cl)
    {
    ComboBox cb = ctr as ComboBox;
    if (ctr !=null)

    {

    (ctr as ComboBox).Text = "";

    }
    }
    }

    ReplyDelete

LinkWithin

Related Posts with Thumbnails