2013-05-08 69 views
0

我有沒有簡單的方法來解釋這一點,但我有100個按鍵,寫了要在按鈕的排列與此這裏行代碼:陣列 - 一個事件處理程序 - 找出哪一個按鈕被點擊

static array <Button^, 2>^ button = gcnew array <Button^, 2> (10,10); 

而且每一個都是初始化這套衣服下面:

button[4,0] = button40; 

我也有所有這些按鈕中的一個事件處理程序。我需要知道的是我可以確定哪個按鈕被點擊的方式,例如,如果單擊第三行和第四列中的按鈕,它應該知道名爲button23的按鈕(在數組中保存爲按鈕[2, 3])已被按下。

另外,這是C++/CLI,我知道這個代碼有多怪。

+0

哇,這是一個地獄很多按鈕和事件處理的! – Goodwine 2013-05-08 20:46:49

回答

1

在事件處理程序,你有事件的sender

void button_Click(Object^ sender, EventArgs^ e) 
{ 
    // This is the name of the button 
    String^ buttonName = safe_cast<Button^>(sender)->Name; 
} 

如果您需要項目的索引(行和列),你通過數組需要循環,因爲Array::IndexOf不支持多維數組。讓我們寫(地方)的通用功能是這樣的:

static void Somewhere::IndexOf(Array^ matrix, Object^ element, int% row, int% column) 
{ 
    row = column = -1; 

    for (int i=matrix->GetLowerBound(0); i <= matrix->GetUpperBound(0); ++i) 
    { 
     for (int i=matrix->GetLowerBound(1); i <= matrix->GetUpperBound(1); ++i) 
     { 
      // Note reference comparison, this won't work with boxed value types 
      if (Object::ReferenceEquals(matrix->GetValue(i, j), element) 
      { 
       row = i; 
       column = j; 

       return; 
      } 
     } 
    } 
} 

所以最後你可能有這樣的:

void button_Click(Object^ sender, EventArgs^ e) 
{ 
    // This is the name of the button 
    String^ buttonName = safe_cast<Button^>(sender)->Name; 

    // This is the "location" of the button 
    int row = 0, column = 0; 
    Somewhere::IndexOf(button, sender, row, column); 
} 
相關問題