Hi Friends,
Yesterday I was resolving a problem. I was getting that I am removing same control from a group box. I am giving you an example. I add 10 same controls dynamically in the group box. Then on one click on Remove button, I need to remove all these controls from group box. The code was written by me was as follows:
foreach (Control ctl in grp1.Controls)
{
if (ctl.GetType().ToString().EndsWith(".ctl1"))
{
grp1.Controls.Remove(ctl);
}
}
When I debug this code, understand the problem that all the controls are not removing from this group box. Then I change the logic with the following one.
int intNoOfControls = grp1.Controls.Count;
for (int i = intNoOfControls - 1; i >= 0; i--)
{
if (grp1.Controls[i].GetType().ToString().EndsWith(".ctl1"))
{
grp1.Controls.Remove(grp1.Controls[i]);
}
}
This code working perfect and resolve the problem. But do you know what was the problem there in for each loop? Its really very interesting. When I am going to remove control from for each loop its removing and compare with the (group box controls -1) controls (i.e. its reinitialize the controls). So its not removing all the controls from the group box.
Note: If you want to add your comments for this article please add it below. Your suggesion are really great advice for me.
Thanks Buddy,
Vijay Modi
Thursday, February 5, 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment