Plunging into .NET Development

Weblog Pieter Gheysens
Microsoft .NET Development - C# - Enterprise Library - Visual Studio 2005 Team System - Compuware DevPartner - ...
 


Thursday, January 20

Batch update of controls on Winforms

Recently I've (re)viewed a lot of GUI-code during the refactoring phase of my project at the client. Today I noticed for example that a lot of User Controls we use contain many of the same control-types like Textboxes, Labels, ... Most of the time these controls are bound to a datasource - no need for a manual update - but in some scenario's these controls must be reset to an empty string for instance. After you set the datasource to null (remove the databinding), you still need to set the Text-property to an empty string. Instead of setting all these Text-properties separately, I've used the following generic method :

        private void clearTextBoxes()

        {

            //Declare type

            Type type = typeof(TextBox);

 

            //Loop into controls on form

            foreach (Control ctrl in this.Controls)

            {

                //check if type of control is TextBox

                if (ctrl.GetType() == type)

                {

                    ctrl.Text = "";

                }

            }

        }


The method above loops into all controls of the form and sets the Text-properties of all TextBoxes to an empty string.

Pff, no big deal really ... but this can be quite powerful (and handy!) if you are able to organize your control-types in some kind of categories so they are subject for a batch update! You can check on the type of control, the name (or substring of the name) of a control, ...

Another example where databinding for textboxes is done in batch may give you more an idea of what I mean :

        private void setDataBindingForTextBoxes()

        {

            //Declare type

            Type type = typeof(TextBox);

 

            //Loop into controls on form

            foreach (Control ctrl in this.Controls)

            {

                //check if type of control is TextBox

                if (ctrl.GetType() == type)

                {

                    //Add DataBinding assuming that name of TextBox is the same as ColumName

                    ctrl.DataBindings.Add("Text", this.myDataSet.Names, ctrl.Name);

                }

            }

        }


These simple procedures also do a lot to the readability of your code and are easy to maintain. I'm sure that this "method" can be used in many more straightforward situations.

0 Comments:

Post a Comment

Links to this post:

Create a Link

<< Home