2016-08-12 16 views
2

NamesDAクラスの中にあるListに基づいてボタンを動的に作成するforeachループを作成するのに問題があります。arraylistに基づいて動的なボタンを作成する方法

次のようなエラーが表示されます。 'Program1.Names'を 'int'に変換できません。私は変換エラーを修正するために知っているすべてを試しましたが、それを行う正しい方法がわかりません。

編集1: allNamesは、csvファイルを読み取るNamesDA内の配列リストです。 これは、文字列と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

アップデートから、allNamesNamesは、クラスを2つのプロパティ/フィールドが含まれている1がであるあるList<Names>、であることは明らかですint型(それは_idとする)であり、別の型はstring型(それは_nameとする)です。したがって、ループを次のように作成する必要があります。

更新:クラス内に2つの整数プロパティ(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'型のオペランドには適用できません。 –

関連する問題