Click here to Skip to main content
15,891,905 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Good day,

i wanted to create a property for my control which lets it add different types of controls, like textbox, label and etc.. I am using a collectionBase to hold my collections, but the return type of the indexer could only be one kind of control.
let's say label. it can only create label and nothing more. how could i change the type that is created just by having another property.

C#
public Label this[int index]
        {
            get
            {
                return (Label)List[index];
            }
        }


this code, will only create a label, how could i change the type to create other kinds of control. Or can someone help me find a generic type for label buttons textbox?

thank you
Posted

The common type behind those controls is "Control". Consequently, use a List<control></control> instead of CollectionBase.
Your property is then:
C#
Public Control this[int index]

You may add specialised functions, e.g.
C#
Public TextBox GetTextBoxAt(int index)
{
    return this[index] as TextBox;
}

Note that it will return null if this[index] is not a TextBox.
 
Share this answer
 
Comments
Rahul Rajat Singh 10-May-12 2:57am    
This is the best way. i recommend this one.

+5
You can't "change the type" of a control - if you declare a TextBox, then it is a TextBox - you can cast it to anything lower down in the chain of things it is derived from but you can't cast sideways. In this case, both Label and TextBox are derived from Control, so you can happily say:
C#
TextBox t = new TextBox();
Label l = new Label();
Control c = (Control) t;
c = (Control) l;
As it happens you don't even need to caste this as it will work perfectly well.
But you can't subsequently say
C#
c = t;
l = (Label) c;
Because it will complain that there is no conversion from a TextBox to a Label.

If what you are trying to do is have an indexer that returns two different types depending on the context it is used in, then you can't - there is (understandably) no mechanism in C# to do that - just like there is no mechanism in C# for two methods differing only in return type.

You could make it generic (MSDN indexers[^] includes a generic example) but you can't do what you want exactly.
 
Share this answer
 
more generic
SQL
public Control this[int index]
{
  get
  {
    return (Control)List[index];
  }
}

And then cast to the specific control type outside of the property maybe.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900