Benyamin Benyamin - 1 year ago 43
C# Question

How to create dynamic buttons based on arraylist

I'm having trouble with creating a foreach loop that creates buttons dynamically based on a List that is in another class.

The namesDA class:

private const string path = "names.csv";
public static List<Names> GetNames()
StreamReader textIn = new StreamReader(new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read));
List<Names> allNames = new List<Names>();
while (textIn.Peek() != -1)
string row = textIn.ReadLine();
string[] columns = row.Split(',');
allNames.Add(new Names(columns[0].ToString(), Convert.ToInt16(columns[1])));

return allNames;

The Form class:

allNames = NamesDA.GetNames(); //calling the method in the NamesDA class
foreach (int x in allNames) {
names[x] = new Button();
names[x].Location = new System.Drawing.Point(startTop + (x * 95), startLeft);

But I get errors such as: Cannot convert type 'Program1.Names' to 'int'. I've tried everything to fix the convert error, but I don't know the correct way to do it.

Edit: allNames is an array list that is in another class that reads a csv file.
It returns a list of strings, which then need to be used to create the buttons.

Answer Source

From the Updates it is clear that allNames is a List<Names>, where Names is a class contains two properties/fields one is of type int(let it be _id) and the another one is of type string(let it be _name). So you have to re create the loop as like the following:

foreach (Names name in allNames) 
    Button tempButton = new Button();    
    tempButton.Name = name._id;
    tempButton.Text = name._name