views:

46

answers:

3

How dan I dynamically create some public properties on a custom webcontrol.

For example, web control has 5 TextBox controls. I need a public property for each TextBox control to be able to set a specific property of the TextBox control.

I want to be able to loop the controls in the webcontrol and create a public property for each TextBox control.

any ideas?

+1  A: 

You could create a property like this

    private TextBox[] textBoxes; //declared as a class member variable

    public TextBox[] TextBoxes
    {
        get
        {
            if (textBoxes == null)
            {
                textBoxes =(from ctrl in this.Controls.OfType<Control>()
                            where ctrl is TextBox
                            select (TextBox)ctrl).ToArray();
            }
            return textBoxes;
        }
    }
mdresser
I need to be able to set the values though....
Alyn
As long as you're not trying to set the collection of textBoxes with this method you should still be ok even though this property is readonly. You would do something like `myControl.TextBoxes[0].Text = "Test";`
mdresser
This will work, but why not just expose the controls as `Public`... Personally I would advice against *both* approaches--exposing controls is wide-open for abuse and bad usages.
STW
A: 

Exposing the controls contained in a WebContol (or any class for that matter) is not a good design as it makes your code brittle and hard to maintain. You should put code that directly manipulates the TextBoxes inside the WebControl.

Panagiotis Kanavos
+1  A: 

Edited:

If the child-controls are present at Design-Time then you need to explain why you want to dynamically add properties to access the control members--unless there is a good reason it just sounds like a poor design.

Here's my suggestion:

  • Leave your controls as Friend or Private -- don't expose them directly (it leads to tight-coupling and gets nasty over time).

  • Expose a new public property that gets/sets the corresponding property on 1x of your controls; so if you want to set .Text on 5x TextBoxes you'll have 5x properties.

  • Be done with it.

If you're trying to be clever by dynamically adding them, then it's a good intention that will lead to poor results. Just remember: KISS (Keep it simple, stupid!).

STW
Present at design time.
Alyn
Then why dynamically add the properties--just add their related properties to the class--in the property setters update corresponding control value.
STW