Thursday, August 7, 2014

How to loop through all textboxes on a form and convert text to integer C#

private void makeStringInt()
        {
           //This is for controls that are on the form
           foreach (Control formControls in this.Controls)
            {
                if (formControls is TextBox)
                {
                    int Integer;
                    if (int.TryParse(formControls.Text, out Integer))
                        formControls.Text = Integer.ToString();
                    else
                        formControls.Text = "";
                }
                if ((formControls.GetType().Name == "GroupBox"))
                {
//This is for controls inside of groupboxes
foreach (Control gbControlsL1 in formControls.Controls)                    {
                        if (gbControlsL1 is TextBox)
                        {
                            int Integer;
                            if (int.TryParse(gbControlsL1.Text, out Integer))
                                gbControlsL1.Text = Integer.ToString();
                            else
                                gbControlsL1.Text = "";
                        }
                        if ((gbControlsL1.GetType().Name == "GroupBox"))
                        {
//This is for controls that are inside of groupboxes that are inside groupboxes
                            foreach (Control gbControlsL2 in gbControlsL1.Controls)
                            {
                                if (gbControlsL2 is TextBox)
                                {
                                    int Integer;
                                    if (int.TryParse(gbControlsL2.Text, out Integer))
                                        gbControlsL2.Text = Integer.ToString();
                                    else
                                        gbControlsL2.Text = "";
                                }
                            }
                        }
                    }
                }
            }
        }
 
This code is designed for controls that have multiple layers of group boxes. When iterating through controls on a form, one must remember that groupboxes hide controls within it. Making an interation that is only for the form, unable to see those controls. Depending on how many panels, groupboxes, tabs, split containers or any other container, you must remember to iterate through those controls as well.

Monday, April 21, 2014

How to loop a CheckedListBox and check if any items are checked C#

        private bool isChecked()
        {
            bool ischecked = false;
            foreach (Object item in checkedListBox.CheckedItems)
            {
                    ischecked = true;
                    break;
            }
            return ischecked;
        }

This is a method that can be called to check if any items in a listbox can are checked. The method returns a bool which can be used in an if statement.