Click here to Skip to main content
14,177,621 members
Rate this:
Please Sign up or sign in to 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.

public Label this[int index]
                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
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

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

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

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

Rate this: bad
Please Sign up or sign in to vote.

Solution 3

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:
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 = 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.
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

more generic
public Control this[int index]
    return (Control)List[index];

And then cast to the specific control type outside of the property maybe.

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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Cookies | Terms of Service
Web06 | 2.8.190526.1 | Last Updated 10 May 2012
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100