2017-07-18 71 views
0

請參閱下面的代碼。代碼將在這裏失敗:person[i].Pic,因爲i未知。PrintDocument:解析索引

如何通過索引iPrintPage() -method?

private void BtnPrint_Click(object sender, EventArgs e) 
{    
    for (int i = 0; i < persons.Count(); i++) 
    { 
     PrintDocument pd = new PrintDocument(); 
     pd.PrintPage += PrintPage; 
     pd.Print(); 
    } 
} 

private void PrintPage(object o, PrintPageEventArgs e) 
{    
    System.Drawing.Image img = System.Drawing.Image.FromFile(person[i].Pic); 
    Point loc = new Point(400, 100); 
    e.Graphics.DrawImage(img, loc); 

} 
+0

使用匿名方法? –

+0

你將他們添加爲事件和訪問全球'人'...不知道你要做什麼,但它聽起來像壞設計 – EpicKip

+0

哦順便說一句,我建議將'人'改爲'人',所以你知道它不是一個局部變量(帕斯卡案例) – EpicKip

回答

1

怎麼是這樣的:

private void BtnPrint_Click(object sender, EventArgs e) 
{    
    for (int i = 0; i < persons.Count(); i++) 
    { 
     PrintDocument pd = new PrintDocument(); 

     pd.PrintPage += 
      delegate(object o, PrintPageEventArgs e) 
      {    
       var img = System.Drawing.Image.FromFile(person[i].Pic); 
       Point loc = new Point(400, 100); 
       e.Graphics.DrawImage(img, loc); 
      }; 

     pd.Print(); 
    } 
} 

即使用可以訪問外部變量ianonymous method