FCI-Helwan blog

Just another FCI-H weblog

How to delete all data from controls in opened forms using C# ???

I will separate this problem into two tasks :
I- Delete all data from one form ( main form )
II- Reaching to other open forms and delete their data .
but before starting , first create a form contain
some combo box ,text box , labels and one button
I- Delete all data from one form ( main form ) :

insert this code in the button you created ( clear button )

private void Clear_Click(object sender, EventArgs e)

{

Control.ControlCollection cc;
cc = this.Controls; // to get all controls of your form

foreach (Control ctrl in cc)

{

string type = ctrl.GetType().ToString();
switch (type)
{
case “System.Windows.Forms.ComboBox”:

ComboBox cb = ctrl as ComboBox;

cb.SelectedIndex = -1;

break;

case “System.Windows.Forms.TextBox”:

TextBox tb = ctrl as TextBox;

tb.Clear();

break;

case “System.Windows.Forms.Label”:

Label L = ctrl as Label;

L.Text = “”;

break;

}

}

}

II- Reaching other open forms and delete their data :

its the easy part , just replace one line code and add a for loop .

replace this line :

cc = this.Controls;

with this line :

cc = Application.OpenForms[i].Controls;

* Application.openforms[i] to reach to all open forms

private void Clear_Click(object sender, EventArgs e)

{

for (int i = 0; i

Control.ControlCollection cc;

cc = Application.OpenForms[i].Controls;

//cc = this.Controls;

// previous code
}

}

}

Advertisements

May 18, 2008 - Posted by | .NET Q and A

1 Comment »

  1. thank you mohamed nabil for your hint
    , you can replace this line :
    string type = ctrl.GetType().ToString();
    and switch statement with :
    If ( ctrl is TextBox )
    {
    // some action
    }

    Comment by Mohamed Abd El hafeez | May 18, 2008 | Reply


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: