Sabtu, 29 Juni 2013

Find a control in windows forms

When we drag-n-drop controls in our designer file then we can easily access those controls in our code file directly by its name. But when we dynamically add some controls either in constructor or in load event of form then we can't access them directly in our code.

Let's have an example

  • Add a textbox and a button using drag-n-drop operation on our form i.e. Form1.
  • Leave the name of controls i.e. textBox1 and button1 as they are.
  • Now in constructor add a new textbox dynamically having name "txtBox" with some properties like:

    TextBox txtBox = new TextBox();
    txtBox.Name = "txtBox";
    txtBox.Text = "dynamically added control";
    txtBox.Width = 250;
    txtBox.Location = new Point(10, 10);

    this.Controls.Add(txtBox);
In above code the Name property will be used to find this control. All the remaining properties are familiar to you as in our designer file. At the last we have added this textbox to the form, here the keyword this is pointing Form1.
This form will look like the following screenshot: 

find control in windows form
 

In click event of button when we will try to access above controls then we notice that "textBox1" will be accessed by its name and "txtBox" will not accessed here.

To access these dynamically added controls we have to use a pre-defined method Find(). This method searches the controls by their name and builds an array as in below code.

Control[] controls = this.Controls.Find("txtBox", false);
foreach (var item in controls)
{
     TextBox txtBox = item as TextBox;
     if (txtBox != null)
        MessageBox.Show("control accessed");
}

In above set of code "controls" will hold the array of all the controls having name "txtBox". One by one we will access items of array and check the type of item. If type of item is TextBox then we found our textbox having name "txtBox".

As we know about naming standards of programming that two controls of the same name cannot exists. Keep in mind the above line, and we are sure that, there will only one control named “txtBox” of type TextBox.

Now we will access the above textbox in one line of code i.e.

TextBox txtBox1 = this.Controls.Find("txtBox", false).First() as TextBox;
if (txtBox1 != null)
 MessageBox.Show("control accessed");

When we run our project and click on button then our form look like this.
find control
 

Tidak ada komentar:

Posting Komentar