I have initialized an ArrayList
in C# for windows form application. I am adding new objects with few properties of each object in the ArrayList
, such as:
ArrayList FormFields = new ArrayList();
CDatabaseField Db = new CDatabaseField();
Db.FieldName = FieldName; //FieldName is the input value fetched from the Windows Form
Db.PageNo = PageNo; //PageNo, Description, ButtonCommand are also fetched like FieldName
Db.Description = Description;
Db.ButtonCommand = ButtonCommand;
FormFields.Add(Db);
Now When I want to check only the FieldName
of each object in the ArrayList
(suppose there are many objects in the ArrayList
). How can I do that??
I tried:
for(int i=0; i<FormFields.Count; i++)
{
FieldName = FormFields[i].FieldName;
}
But this is generating error (in the IDE). I am new to C# programming, so can someone help me with this??
Error: Error 21 'object' does not contain a definition for 'FieldName' and no extension method 'FieldName' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
Finally figured out the answer. I tried to cast the objects for each object saved in the arraylist and finally could fetch the required field of each object:
for (int i = 0; i < FormFields.Count; i++)
{
CDatabaseField Db = (CDatabaseField)FormFields[i];
Label1.Text = Db.FieldName; //FieldName is the required property to fetch
}
ArrayList
holds objects. It's not generic and type safe.That's why you need to cast your object to access it's properties. Instead consider using generic collections like List<T>
.
var FormFields = new List<CDatabaseField>();
CDatabaseField Db = new CDatabaseField();
...
FormFields.Add(Db);
Then you can see that all properties will be visible because now compiler knows the type of your elements and allows you to access members of your type in a type-safe manner.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With