2016-08-12 38 views
2

我無法創建一個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]); 
} 
+0

'NamesDA.GetNames()'返回什麼類型? 'all'是什麼類型? –

+0

您正在分配'names [x]',但您要添加'allNames [x]'。 – dasblinkenlight

+0

有幾個變量在給定的片段('names','all')中是未定義的,您能否定義它們? –

回答

1

從更新顯然allNamesList<Names>,其中Names是一類包含兩個屬性/字段之一是鍵入int(讓它爲_id),另一個是字符串類型(讓它爲_name)。因此,您必須重新創建循環,如下所示:

更新:如果您需要定義類中的兩個整數屬性(讓它爲int positionX=10int PositionY=30),也可以設置按鈕位置,現在看看更新後的代碼:

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; 
} 
+1

是的,它似乎是答案.... –

+0

這正是我正在尋找的。謝謝。 –

+0

你知道我怎麼能夠設置位置嗎? btn.Location = new System.Drawing.Point(startTop +(x * 95),startLeft);其說法的運算符*不能應用於名稱類型和'int'類型的操作數。 –