2017-10-23 16 views
1

.CSVファイルにアクセスしてDataGridに表示する値を変換していますが、私の問題は定義済みのインスタンスが1つしかなく、ループの外側にあるため、プロパティを設定します。複数のインスタンスを作成してプロパティ値を設定する

ループ内で複数のインスタンスを作成し、プロパティ値を設定するにはどうすればよいですか?

CSV形式である: 'ヘッダ' ここに文字列、文字列、整数、文字列 '(300件のエントリまで)

はメニュー - をクリックから呼び出さ主コード、>オープンである:

ここで
 // Function to open a .CSV file and assign the values within to a List. 
    private void openToolStripMenuItem_Click(object sender, EventArgs e) 
    { 
     List<Stock> stocks = new List<Stock>(); 
     // Set strings to retrieve current directory and store stocklist.csv as "filename" 
     string filename = @"C:\StockFile\stocklist.csv"; 

     // Read all lines in file and set indexer to 0. 
     string[] linesInFile = File.ReadAllLines(filename); 
     string[] StockDetails = new string[0]; 

     for (int i = 1; i < linesInFile.Length; i++) 
     { 
      // Load lines in file and increment by 1. 
      string currentLine1 = linesInFile[i]; 
      // Split the current line by separator , 
      StockDetails = currentLine1.Split(','); 

      Stock item = new Stock(); 
      stocks.Add(item); 
     } 
     var list = new BindingList<Stock>(stocks); 
     stockGridView.DataSource = list; 
    } 

は私のストッククラスである:

class Stock 
    { 
     public string Code { get; internal set; } 
     public string Desc { get; internal set; } 
     public int CurCnt { get; internal set; } 
     public string Order { get; internal set; } 

     public Stock(string code, string desc, int curcnt, string order) 
     { 
      Code = code; 
      Desc = desc; 
      CurCnt = curcnt; 
      Order = order; 
     } 
    } 

答えて

0

私はあなたがやろうとしているかを理解する場合は、あなたが株のインスタンスを初期化する必要がありますアイテムに追加され、ループのたびに新しいキーワードが作成され、作成されたインスタンスがリストに追加されます

private void openToolStripMenuItem_Click(object sender, EventArgs e) 
    { 
     List<Stock> stocks = new List<Stock>(); 
     // Set strings to retrieve current directory and store stocklist.csv as "filename" 
     string filename = @"C:\StockFile\stocklist.csv"; 

     // Read all lines in file and set indexer to 0. 
     string[] linesInFile = File.ReadAllLines(filename); 
     string[] StockDetails = new string[0]; 

     for (int i = 1; i < linesInFile.Length; i++) 
     { 
      // Load lines in file and increment by 1. 
      string currentLine1 = linesInFile[i]; 
      // Split the current line by separator , 
      StockDetails = currentLine1.Split(','); 

     Stock item = new Stock(StockDetails[0],StockDetails[1],StockDetails[2],StockDetails[3]); 
    stocks.Add(item); 
     } 
     var list = new BindingList<Stock>(stocks); 
     stockGridView.DataSource = list; 
    } 
+0

完全に、私が紛失していたことは今や目立って明らかです私はこの物語の初心者だと言うことができるとうれしいです。ハハ。 データグリッドは、リストから完全に(プレースホルダ以外のものになるように列名を調整した後で)完全に入力されます。 –

関連する問題