Form objects and controls

  • Thread starter Thread starter Ann Marinas
  • Start date Start date
A

Ann Marinas

Hello!

Is it possible to get all of your controls in a form and store it in a
collection (for populating puposes)?
If yes, how can you store it and retrieve it while determining the element's
type?

Like for example, I have many textboxes and buttons and labels in my form,
and I want to populate the textboxes with the data that I got from the
database,

How can I achieve this by using collections instead of explicitly assigning
which textbox is for a specific data column?

Thank you so much!

A :D
 
Ann Marinas said:
Hello!

Is it possible to get all of your controls in a form and store it in a
collection (for populating puposes)?
If yes, how can you store it and retrieve it while determining the element's
type?

Sure! In fact, they already did it for you:

(in your form code)

this.Controls

or the Form.Controls property.
Like for example, I have many textboxes and buttons and labels in my form,
and I want to populate the textboxes with the data that I got from the
database,

How can I achieve this by using collections instead of explicitly assigning
which textbox is for a specific data column?

When the form is initialized, in the InitializeComponent() method,
when the various textboxes are added to the Controls collection, you
can create your own ArrayLists or Hashtables for each type of
control collection you wish to create.

For example, you could have a Hashtable of textboxes where the key
is the field name in the database.

So when you're loading a SqlDataReader or a DataTable or whatnot,
you can just use the current column's columnname and get the
corresponding textbox and set it's text value.

-c
 
Thank you so much!

I really appreciate it! :D


MP said:
I don't know exactly what to you need, but this is an example with the idea

using System.Reflection;
...
foreach(Control c in yourControl.Controls)
{
switch (c.GetType().Name.ToString())
{
case "TextBox":
TextBox tb = (TextBox) c;
tb.ReadOnly = true;
break;
...
I hope this help...

MP
 
Thank you, Chad! :D


Chad Myers said:
Sure! In fact, they already did it for you:

(in your form code)

this.Controls

or the Form.Controls property.


When the form is initialized, in the InitializeComponent() method,
when the various textboxes are added to the Controls collection, you
can create your own ArrayLists or Hashtables for each type of
control collection you wish to create.

For example, you could have a Hashtable of textboxes where the key
is the field name in the database.

So when you're loading a SqlDataReader or a DataTable or whatnot,
you can just use the current column's columnname and get the
corresponding textbox and set it's text value.

-c
 
Hi,

This method will not get you the dynamic controls, it's better to use the
Control collection for that.

Hope this help,
 
Back
Top