Reputation:
I'm having some trouble creating a foreach loop that creates buttons dynamically based on a List that is inside the NamesDA class.
I'm getting errors such as: Cannot convert type 'Program1.Names' to 'int'. I've tried what I know to fix the conversion error, but I don't know the correct way to do it.
Edit 1: allNames is an array list inside NamesDA that reads a csv file. It returns a list of strings and int's, which then they are to be used to create the buttons and represent them.
Edit 2: The foreach loop problem is solved now, but I'm unable to get the values of column[0] for button text and column[1] for button tag.
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])));
}
textIn.Close();
return allNames;
}
The form:
int startTop = 20;
int startLeft = 17;
allNames = NamesDA.GetNames(); //calling the method in the NamesDA class
foreach (int x in allNames) {
names[x] = new Button();
tempButton.Text = ""; //based on the list column[0]
tempButton.Tag = ""; //based on the list column[1]
names[x].Location = new System.Drawing.Point(startTop + (x * 95), startLeft);
listView.Controls.Add(names[x]);
}
Upvotes: 2
Views: 1222
Reputation: 29026
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:
Updates : You can Set the button location as well, if you need that you have to define two integer properties in the class(let it be int positionX=10
and int PositionY=30
) Now take a look at the updated code:
int nextLeft=30;
foreach (Names name in allNames)
{
Button tempButton = new Button();
tempButton.Name = name._id;
tempButton.Text = name._name;
tempButton.Location = new System.Drawing.Point(name.positionX + nextLeft,name.positionY);
listView.Controls.Add(tempButton);
nextLeft+=30;
}
Upvotes: 1