我無法創建一個foreach循環,基於名稱DA類內的List動態創建按鈕。如何創建基於arraylist的動態按鈕
我收到錯誤,如:無法將類型'Program1.Names'轉換爲'int'。我已經試過了解修正轉換錯誤的所有信息,但我不知道正確的方法。
編輯1: allNames是NamesDA中的一個數組列表,它讀取一個csv文件。 它返回一個字符串和int的列表,然後它們將被用來創建按鈕並表示它們。
編輯2:現在已經解決了foreach循環問題,但我無法獲得按鈕標記的按鈕文本的列[0]和列[1]的值。
的NamesDA類:
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;
}
形式:
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]);
}
'NamesDA.GetNames()'返回什麼類型? 'all'是什麼類型? –
您正在分配'names [x]',但您要添加'allNames [x]'。 – dasblinkenlight
有幾個變量在給定的片段('names','all')中是未定義的,您能否定義它們? –