2013-06-01 27 views
3

我正在使用「for」爲PictureBox數組賦值。 對於每個PictureBox,我需要點擊事件。 當我點擊它時,我需要接受點擊的PictureBox的一些值,但由於它是它們的數組,所以我需要向事件發送「for」計數器的值,該值指定點擊的PictureBox(您的指數)。C# - 發送值的Click事件

我的代碼如下所示:

PictureBox[] picboxes = new PictureBox[result]; 
for (int i = 0; i < results; i++) 
{ 
    picboxes[i] = new PictureBox(); 
    picboxes[i].ImageLocation = @FormIni.RetRes((i * 5) + 5 + i); 
    picboxes[i].Click += new System.EventHandler(PictureBoxes_Click); 
} 

private void PictureBoxes_Click(object sender, EventArgs e) 
{ 
    label1.Text = "here I need the value of the picboxes[i] image location"; 
} 

它看起來愚蠢,但我認爲是這樣的:

picboxes[i].Click += new System.EventHandler(PictureBoxes_Click(i))

private void PictureBoxes_Click(object sender, EventArgs e, int i)

彙總:當我點擊一個PictureBox cr通過代碼在數組中消失,我需要接收它的值,但是如何?如何獲得數組picboxes中的值(在點擊事件中),因爲我需要您的索引?

這對我來說是一個很大的麻煩。

編輯!

在提出這個問題後,我很抱歉找到這個問題,但我發現these可以工作的解決方案。我對嗎?

回答

4

嘗試做做這個

PictureBox[] picboxes = new PictureBox[result]; 
for (int i = 0; i < results; i++) 
{ 
    picboxes[i] = new PictureBox(); 
    picboxes[i].Name = (i+1).ToString(); 
    picboxes[i].ImageLocation = @FormIni.RetRes((i * 5) + 5 + i); 
    picboxes[i].Click += new System.EventHandler(PictureBoxes_Click); 
} 

private void PictureBoxes_Click(object sender, EventArgs e) 
{ 
    PictureBox p = (PictureBox)sender; 
    string j = p.Name; 
    label1.Text = j; 
} 
0

您可以使用以下(anoynomous法)lambda表達式

picboxes[i].Click += (sender, eventArguments) => PictureBoxes_Click(sender, eventArguments, i); 
+0

謝謝,但我從未使用過lambda表達式,所以它混淆了我。 =/ –

+0

它使編碼在我看來更容易。嘗試一下,看看它是否有效。 –