ASP.Net + Removing controls from groupbox using ForEach loop

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

Advertisements

About Vijay Modi

Having 12+ years of experience in web application development. Expertise in various domains like E-Commerce, E-Learning, Insurance. I have expertise in web application development, window application development, Performance improvement, bug fixing etc. I have worked on various Microsoft technologies including ASP.Net, MVC, WebApi, WCF, Entity Framework, WPF, Window Application Development, AWS, Azure, AngularJS 2.0 / 1.5.2, .NetCore framework, jQuery. I am believing in quality work and achieving deadlines. Also like to work on new technologies and quick learner.
This entry was posted in Uncategorized and tagged . Bookmark the permalink.

3 Responses to ASP.Net + Removing controls from groupbox using ForEach loop

  1. Alex buchan says:

    Thanks – this helped me search for controls within a group box. But the real reason I am writing is to ask – what is going on in the picture? – you look to be having far too much fun!

  2. Pavan says:

    Hi,
    Ur Article so helpful me in one of my project development. And Still now i did’nt understand why the problem getting with “foreach” & “for “.
    Where the problem is resovled with “for “. If u have chance to explain me, just consider my problem.

    My Task is ” I developed an application by retrieving a list of Tables from the database into combobox. I choosed a table & Clicked ‘OK’ button, That Table should be display into the groupbox1 with labels & Textboxes. And when i choosed another Table from Combobox, old controls should be remove from the groupbox1 & again new controls should be generate according to numberofcolumns, fieldnames.

    If u wana see my code:

    ———————————————————————————————–
    public void RemoveCtrls()
    {
    //MessageBox.Show(gb_DataBox.Controls.Count.ToString());

    //foreach (Control ctrl in gb_DataBox.Controls)
    //{
    //if (!(ctrl is Button))//(ctrl.GetType() == typeof(Button)) //(((Button)ctrl).Text != “Next”)
    //{
    // MessageBox.Show(ctrl.GetType().Name + ” : ” + ctrl.Name.ToString());
    // gb_DataBox.Controls.Remove(ctrl);
    // ctrl.Dispose();
    //}
    // }

    int c = gb_DataBox.Controls.Count;

    //for (int i = 1; i = 0; i–)
    {
    if (!(gb_DataBox.Controls[i] is Button))
    {
    //if (gb_DataBox.Controls[i].GetType().ToString())//.EndsWith(“.ctl1″))

    MessageBox.Show(gb_DataBox.Controls[i].GetType().Name + ” : ” + gb_DataBox.Controls[i].Name.ToString());
    gb_DataBox.Controls.Remove(gb_DataBox.Controls[i]);
    }
    }
    }

    private void btn_ConnectDB_Click(object sender, EventArgs e)
    {
    //Make Default values
    y = 20;
    gb_DataBox.Height = 100;//50;

    RemoveCtrls();
    //cn = new SqlConnection(“Data Source=.;Initial Catalog=master;User ID=sa;Password=123”);

    query = txtQuery.Text;
    try
    {
    cmd = new SqlCommand(query, cn);

    if (cn.State == ConnectionState.Open)
    cn.Close();

    cn.Open();
    dr = cmd.ExecuteReader();

    lb = new Label[dr.FieldCount];
    txt = new TextBox[dr.FieldCount];

    for (int i = 0; i < lb.Length; i++)
    {
    lb[i] = new Label();
    txt[i] = new TextBox();
    lb[i].Text = dr.GetName(i);
    lb[i].Name = dr.GetName(i);
    txt[i].Name = dr.GetName(i);
    lb[i].Location = new Point(100, y + 3);
    txt[i].Location = new Point(200, y);
    //MessageBox.Show(lb[i].Text.ToString());
    //MessageBox.Show(txt[i].Name.ToString());
    gb_DataBox.Controls.Add(lb[i]);
    gb_DataBox.Controls.Add(txt[i]);
    y += 30;

    gb_DataBox.Height += txt[i].Height;// +3;
    this.Height = groupBox2.Height + gb_QueryBox.Height + gb_DataBox.Height + 100;
    //this.AutoScroll = true;
    int c = gb_DataBox.Controls.Count;
    }
    }
    catch (Exception ex)
    {
    MessageBox.Show(ex.Message);
    cn.Close();
    }
    btn_Next.Enabled = true;
    }

    private void btn_Next_Click(object sender, EventArgs e)
    {
    if (dr.Read())
    {
    for (int i = 0; i < lb.Length; i++)
    txt[i].Text = dr.GetValue(i).ToString(); //dr[i].ToString();
    }
    else
    {
    MessageBox.Show("No More Records..");
    cn.Close();
    btn_Next.Enabled = false;
    }
    }
    ————————————————————————————————

    For Picture : http://myarticles-csharpnetstuff.blogspot.com/2010/11/createremove-controls-infrom-containers.html

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