Removing Componets (exp Checkboxes )

If I wanted to lets say... have a few checkboxes right... and I wanted to remove the ones that are checked... how do I do that Like.. remove the checkbox right along with its value.



Answer this question

Removing Componets (exp Checkboxes )

  • R Korman

    You seem greatly confused about dealing with collections. You are going to a lot of needless effort.


    string[] input = str.Split( new char[] { ' ', '\n' });

    This line is fine. Keep it.


    List<string> list = new List<string>();
    for( int x = 0; x < input.Length; x++ )
    {
    list.Add( input[x] );
    }

    These lines could be reduced to just:

    List<string> list = new List<string>(input);

    Or you could just drop them entirely. There's nothing that you need to do that can't be done with input[].


    string[] strings = list.ToArray();

    Similarly, you can drop this. There's nothing that you need to do that can't be done with input[].


    CheckBox[] chk = new CheckBox[strings.Length];

    Again, you can drop this. You never work with more than one checkbox at a time. There's no need to keep them in an array.


    for( int x = 0; x < strings.Length; x++ )
    {
    if( Regex.IsMatch( strings[x], @"^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$" ) == false && strings[x].Length < 1 )
    {
    Be sure to change all references from strings[] to input[]


    for( int x = 0; x < input.Length; x++ )
    {
    if( Regex.IsMatch( input[x], @"^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$" ) == false && input[x].Length < 1 )
    {

    Skipping a bit....


    chk[x] = new CheckBox();
    chk[x].Location = new Point( 10, 30 * x );
    chk[x].Size = new Size( 350, 40 );


    Since we dropped the chk array above, we can make this a single checkbox here:

    CheckBox chk = new CheckBox();
    chk.Location = new Point( 10, 30 * x );
    chk.Size = new Size( 350, 40 );

    Then...


    if( chk[x].Text == "" )
    {
    indexes.Add(x);
    pnl2.Controls.Remove( chk[x] );
    }
    The if() makes no sense whatsoever. The CheckBox was just created. It's text property cannot help but be empty. Further, since it was never added to pnl2's controls (it could not have been, as it was just created), it canot be removed from the panel. Finally, it's unclear why you are creating an arraylist with 1,2,3..etc in it.



  • ANB_149

    The second method won't work as you can't modify a collection that is being iterated over.

    Neither of the posted examples attempt to modify a collection that's being iterator over Both use two separate collections, which is why both have two loops.



  • aero1

    Hi

    Dont forget that foreach isn't only loop what we have:

    int i = 0;
    while (i < panel1.Controls.Count)
    {
    CheckBox cb = panel1.ControlsIdea as CheckBox;
    if (cb != null && cb.Checked)
    panel1.
    Controls.Remove(cb);
    else
    i++;
    }


  • Annihil8

    The second method won't work as you can't modify a collection that is being iterated over. The first is fine, but why not do it in a single pass (i.e. do the first loop in reverse order and remove the controls as you find them).

  • tirengarfio

    ok here I go again :-S I'm back to square one on this removing checkboxes stuff... but.. I actually need to remove selected checkboxes.. and also.. empty checkboxes... you know like.. checkbox.Text == "" (I need to remove these empty chks ) so far what I have is...

    List<string> list = new List<string>();
    ArrayList indexes = new ArrayList();
    string[] input = str.Split( new char[] { ' ', '\n' });

    for( int x = 0; x < input.Length; x++ )
    {
    list.Add( input[x] );
    }

    Console.WriteLine( pnl2.Controls.Count );

    string[] strings = list.ToArray();

    CheckBox[] chk = new CheckBox[strings.Length];

    for( int x = 0; x < strings.Length; x++ )
    {
    if( Regex.IsMatch( strings[x], @"^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$" ) == false && strings[x].Length < 1 )
    {
    MessageBox.Show( strings[x], "Incorrect IP Format", MessageBoxButtons.OK, MessageBoxIcon.Exclamation );

    }else{

    if( strings[x] != null && strings[x] != "" && strings[x] != "\n" )
    {
    try {

    IPHostEntry ipHostEntry = Dns.GetHostEntry( strings[x].ToString());

    chk[x] = new CheckBox();
    chk[x].Location = new Point( 10, 30 * x );
    chk[x].Size = new Size( 350, 40 );

    if( chk[x].Text == "" )
    {
    indexes.Add(x);
    pnl2.Controls.Remove( chk[x] );
    }

    chk[x].Text = ipHostEntry.HostName;

    pnl2.Controls.Add( chk[x] );

    }catch( Exception exc ) {

    MessageBox.Show( strings[x] + " Is an Incorrect IP Address", exc.Message, MessageBoxButtons.OK, MessageBoxIcon.Exclamation );
    }
    }
    }


    sorry :S Just trying to learn and understand stuff... so that I can help others like others help others.. errr you get the point :)  

    The thing is that if I don't remove the empty checkboxes.. then It will print on the panel and it will leave a gap between other hostnames... then later on I need to remove the onces selected... but I think that If I can get the empty ones removed.. then I guess it should be the same as removing the selected one :S

    ------ Edit ------------

    Got one error fixed... when I get a blank field in the panel :-) now to code up the remove button part.


  • Rei Miyasaka

    what I really need is to remove them.. because I'm creating a program that will check against IPs

    I fail to see a causal relationship between those two statements.   Similarly, I fail to see the causal relationship in these statements:

    I'm using a for loop not a for each loop.. because I also have a textbox that grabs information then splits it according to the information provided
    but at least in this case I can address it.  Your code


    for( int x = 0; x < strings.Length; x++ )
         {
         if( strings[x] != "" && strings[x] != null )
         {

     

    is essentially the same as:


    for( string stringx in strings)
         {
         if( stringx != "" && stringx != null )
         {

     

    Further, on the if(), you'd really want to do the null-check before you do anything else with it.  Also checking for Length = 0 is slighter faster than comparing with "":


    for( string stringx in strings)
         {
         if( stringx != null && stringx.Length != 0)
         {

     

    Other, mostly stylistic things to look at:

    - At some times "grp" refers to a class data member, at other times, it's a parameter (althought it always refers to the same actual GroupBox). This could get confusing.  It's suggest renaming the data member (to say "m_grp" - or maybe "m_groupBox" -- typing's really not that hard), and have all the methods that use it take a GroupBox parameter- although since you never use a GroupBox specific method or property in any of the methods shown here, you might want to pass it around as just a Control.

    - I'd say it would be a bad idea to call a method which adds a text box from within a method called "AddButtons".  Consider some other user of this code --- he cal a method named "Add Buttons" thinking he's going to get buttons -- and he actually gets buttons and a text box. I'd suggest moving that call to AddPanel --- hmmm... Same problem there, but this time it's not quite that bad -- a text box (and button) could properly be part of a panel.  How 'bout we just rename it to make it's job clearly, to say "BuildPanel"

     

     

     



  • Scott Bellware

    Do you need such a big font It's as rude as all caps.

    That wasn't my idea. Blame it on the wackiness of this editor. I believe the problem started when I tried the quote button, which put things in a really small font. I tried to enlarge them to what look like a normal size in the editor, which became huge when I posted it.



  • CaptainSmudge

    Hi,
    I assume you want to remove (not uncheck) the checkboxes from a control right So, this is a possible solution (I'm using a panel has the parent of the checkboxes, just replace the panel with what you want):

    // gather which checkboxes are checked
    ArrayList indexes = new ArrayList();
    for(int i = 0; i < panel1.Controls.Count; i++)
    {
        CheckBox chk = panel1.Controls[ i ] as CheckBox;
        // is this control a checkbox and is it pressed add it to the list if so
        if(chk != null && chk.Checked)
        {
            indexes.Add(i);
        }
    }

    // remove from last to first or else the index of the items in the panel.Controls will not coincide.
    for (int i = indexes.Count - 1; i >= 0; i--)
    {
        panel1.Controls.RemoveAt((int)indexes[ i ]);
    }



  • JoneLee

    Apologies, it was the naming that confused me "theControls" looks very much like "this.Controls".

    As I said though, it could be done in one loop.

    Do you need such a big font It's as rude as all caps.



  • Andreas Drake

    hey James Curran, thanx for the information.. It was pretty informative... now.. I can use your recommendations.. and to remove it I can some some of the example codes above correct I mean.. looking at the code that I added. Also can anyone point me to the right faq on how to wrap codes in code tags


  • The Admiral

    Ok... thanx I will try it out and post back the results.... thanx bro


  • mEt

    what I really need is to remove them.. because I'm creating a program that will check against IPs... but never mind that part for now... also.. I'm using a for loop not a for each loop.. because I also have a textbox that grabs information then splits it according to the information provided.. then added it in to an arraylist.. then loop it.. anyways.. just incase here is the code..

     

    [code]

    using System;
    using System.Windows.Forms;
    using System.Drawing;

    class App
    {
       public static void Main()
       {
          Application.Run( new MyApp());
       }
    }

    class MyApp : Form
    {
        private TextBox        txt;
        private CheckBox[]     chk = new CheckBox[10];
        private Panel          pnl, pnl2;
        private GroupBox       grp;
        private StatusBar      stb;
        private StatusBarPanel stbp;

        public MyApp()
        {
           this.MaximizeBox = false;

           this.Size = new Size( 800, 600 );
           this.Text = "Host Scanner";

           stb       = new StatusBar();
           stb.Size  = new Size( 400, 24 );
           stbp      = new StatusBarPanel();

           stbp.Text     = "Ready";
           stbp.AutoSize = StatusBarPanelAutoSize.Spring;
           stbp.Icon     = new Icon( Application.StartupPath + "\\host.ico" );

           stb.ShowPanels = true;
           stb.SizingGrip = false;

           stb.Panels.Add( stbp );

           grp          = new GroupBox( );
           grp.Size     = new Size( 400, 300 );
           grp.Location = new Point( 10, 10 );
           grp.Text     = "Scan IP";

           AddPanel();
           AddSecondPanel();

           this.BackColor   = Color.Silver;
           this.Controls.Add( stb );

        }

        void AddPanel()
        {
            int width        = this.Size.Width;
            int height       = this.Size.Height;

            pnl              = new Panel();
            pnl.Size         = new Size( 420, 320 );
            pnl.Location     = new Point( 3, 0 );
            pnl.BackColor    = Color.Silver;
            pnl.AutoScroll   = true;
            //pnl.BorderStyle  = BorderStyle.Fixed3D;

            AddButtons( grp );
            AddMenu( grp );

            pnl.Controls.Add( grp );
            this.Controls.Add( pnl );
        }

        void AddSecondPanel()
        {
             pnl2             = new Panel();
             pnl2.Location    = new Point( 425, 0 );
             pnl2.Size        = new Size( 365, 320 );
             pnl2.AutoScroll  = true;

             //pnl2.BorderStyle = BorderStyle.Fixed3D;
             pnl2.BackColor   = Color.Silver;

             this.Controls.Add( pnl2 );
        }

        void AddButtons( GroupBox grp )
        {
           Button btn    = new Button();
           Button btnc   = new Button();

           btn.Location  = new Point( 5, 268 );
           btnc.Location = new Point( 100, 268 );

           btn.Click    += new EventHandler( btn_click );
           btnc.Click   += new EventHandler( btn_clear );

           btn.Size      = new Size( 80, 23 );

           btn.Text      = "Start Scaning";
           btnc.Text     = "Clear";

           grp.Controls.Add( btn );
           grp.Controls.Add( btnc );

           AddTextArea( grp );
        }

        void AddTextArea( GroupBox grp )
        {
            txt           = new TextBox();
            txt.Size      = new System.Drawing.Size( 390, 230 );
            txt.Location  = new Point( 5, 30 );

            txt.Multiline = true;
            txt.ScrollBars = ScrollBars.Vertical;

            grp.Controls.Add( txt );
        }

        void AddMenu( GroupBox grp )
        {
            MainMenu mnu  = new MainMenu();
            MenuItem mnuF = new MenuItem( "&File" );
            MenuItem mnuA = new MenuItem( "&Help" );

            mnuA.MenuItems.Add( "About", new EventHandler( AboutProg ));
            mnuF.MenuItems.Add( "Close", new EventHandler( WindowClose ));

            mnu.MenuItems.Add( mnuF );
            mnu.MenuItems.Add( mnuA );

            this.Menu = mnu;
        }

        void btn_click( object obj, EventArgs ea )
        {
            Button btn = (Button)obj;
      
            if( btn.Text == "Start Scaning" )
                UpdateInformation( txt.Text );
        }

        void UpdateInformation( string str )
        {
         string[] strings = str.Split( ' ' );
         //Checkbox[] chk   = new Checkbox[strings.Length];
        
         for( int x = 0; x < strings.Length; x++ )
         {
         if( strings[x] != "" && strings[x] != null )
         {
             chk[x]     = new CheckBox();
          chk[x].Location = new Point( 10, 30 * x );
             chk[x].Size    = new Size( 350, 40 );
             chk[x].Text    = strings[x];
            
             pnl2.Controls.Add( chk[x] ); 
            }    
         }   
        }

        void btn_clear( object obj, EventArgs ea )
        {
            Button btnclear = (Button)obj;

            if( btnclear.Text == "Clear" )
                txt.Text = "";
        }

        void AboutProg( object obj, EventArgs ea )
        {
             Console.WriteLine( "About the Program" );
        }

        void WindowClose( object obj, EventArgs ea )
        {
             this.Close();
        }
    }

    [/code]

     

    Remember I'm still new at c sharp so bare with me please. Also how do you put codes inside code tags



  • Olivier .NET

    small variation, results in the same thing really just FYI

    ArrayList theControls = new ArrayList();

    foreach(Control curControl in this.Controls)

    {

    if (curControl.GetType().Equals(typeof(CheckBox)))

    {

    if (((CheckBox)curControl).Checked)

    {

    theControls.Add(curControl);

    }

    }

    }

    foreach(Control currentItem in theControls)

    {

    this.Controls.Remove(currentItem);

    }



  • ljames28

    What exactly do you mean by "remove". I'm gonna guess that hiding the checkbox would be sufficent:


    foreach(Control ctl in panel1.Controls)
    {
    CheckBox chk = ctl as CheckBox;
    if(chk != null && chk.Checked)
    {
    chk.Visible = false;
    }
    }



  • Removing Componets (exp Checkboxes )