Reputation: 171
I can't seem to figure out how to access specific properties of each object contained within a list. For example, if I reference the object outside of the list (prior to passing it to the button click), I can see properties like "tag", "height", "width", etc. (all the standard properties for that type). However, I cannot figure out how to access those object-specific properties once the list has been passed to my button click event.
Please refer to this example:
private TextBox createTextBox(string name)
{
// Create TextBox Code is Here
TextBox dTextBox = new TextBox();
dTextBox.Name = name;
dTextBox.Tag = "sometag";
dTextBox.Height = 12345;
dTextBox.Width = 12345;
return dTextBox;
}
private void some_function()
{
var objectList = new List<Object>();
objectList.Add(createTextBox("example1"));
objectList.Add(createTextBox("example2"));
objectList.Add(createTextBox("example3"));
}
private int button_click(object sender, EventArgs e, Int32 ticketGroupID, List<Object> objectList)
{
for(int i = 0; i < objectList.Count(); i++)
{
Int32 valuableInfo = objectList[i].?? // Here is where I am trying to access specific properties about the object at index i in the list, such as the objects TAG, VALUE, etc. How can this be done?
// do things with the valuable info
};
}
Thanks in advance for any assistance.
Upvotes: 1
Views: 70
Reputation: 4895
You can either check type
first, then cast it to TextBox
later or reverse.
See example below:
foreach (var obj in objectList)
{
// method 1: check first, cast later
if (obj is TextBox)
{
Int32 valueableInfo = ((TextBox)obj).Height;
}
// method2: cast first, check later
var textBox = obj as TextBox;
if (obj != null)
{
Int32 valueableInfo = obj.Height;
}
}
Upvotes: 0
Reputation: 49974
It's a List<> which implements IEnumerable<T>
, so you can make use of the OfType<T>()
method to extract items that are already strongly typed and ready for you to access:
var myListOfTypedObjects = myList.OfType<TextBox>();
myListOfTypedObjects.ForEach(tb => Console.Writeline(tb.Name));
Upvotes: 1
Reputation: 30813
You need to make the object
strongly-typed. That is, to cast it to your class
:
Int32 valuableInfo = ((TextBox)objectList[i]).Height; //now you can access your property
Otherwise, you cannot access the properties of the class because the compiler wouldn't know what is the actual type of the object
. Also, your Intellisense will just deemed it as object
, not your strongly-typed class (example: MyClass
, or in your case, the class being TextBox
)
Upvotes: 1