I'm trying to add objects of DataPerLabel
to my Arraylist allData
, following the code of DataPerLabel
:
class DataPerLabel
{
public String labelName;
public String labelAdress;
public String dataType;
public DataPerLabel(String labelName, String labelAdress, String dataType)
{
this.labelName = labelName;
this.labelAdress = labelAdress;
this.dataType = dataType;
}
public String getLabelName()
{
return labelName;
}
public String getLabelAdress()
{
return labelAdress;
}
public String getDataType()
{
return dataType;
}
}
In the following code I try to add the objects of DataPerLabel
to my arraylist
:
submitButton.Click += (sender, args) =>
{
String label = textboxLabel.Text;
String adress = textboxAdress.Text;
String dataType = "hey";
if (buttonsLabelBool.Checked)
{
dataType = "Bool";
}
else if (buttonsLabelReal.Checked)
{
dataType = "Real";
}
else if (buttonsLabelInt.Checked)
{
dataType = "Int";
}
allData.Add(new DataPerLabel(label, adress, dataType));
};
And finally I try to read out the arrayList
by displaying it in a textbox
, see the following code:
private void test()
{
Button btn = new Button();
btn.Location = new Point(500,500);
btn.Text = "test";
btn.Click += (sender, args) =>
{
foreach (var item in allData)
{
//Display arraylist per object here
//Something like : item.getLabelName();
}
};
}
I'm not sure what I'm doing wrong, hope you can help!
ArrayList
stores a list ofSystem.Object
. You need to cast the object back toDataPerLabel
as follows:Alternatively, you could specify the data type in the foreach instead of
var
as Jakub Dąbek pointed out in the comment as follows:A better approach would be to use generic list/collection
List<DataPerLabel>
to store the data so that the casting can be avoided.Yiu should use a
List<T>
instead ofArrayList
. This way every item in your list has the right type already and you can access the members:This assumes
allData
is defined like this:instead of
allData = new ArrayList()
If you really have to use an
ArrayList
than you should cast your item to the actual type. The code above actually does this allready. However you could also use this: