This blog is subject the DISCLAIMER below.

Sunday, May 18, 2008

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
}

}

}


1 comment:

Mohamed Abd El hafeez said...

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
}