2015-07-13 124 views
0

我在DataGridView中創建了TableLayoutPanel。那麼,如何爲每個datagridview右鍵單擊事件? 這裏是動態的DataGridView創建源代碼如何將鼠標右鍵點擊事件動態創建datagridview

public void makeDataGridView(int num) 
    { 
     for (int i = 0; i < num; i++) 
     { 
      DataGridView[] dgv = new DataGridView[num]; 

      dgv[i] = new DataGridView(); 
      dgv[i].Name = "dgv" + i.ToString(); 
      tableLayoutPanel1.Controls.Add(dgv[i]); 
     } 
    } 

回答

0

你可以試試這個

public void makeDataGridView(int num) 
{ 
    for (int i = 0; i < num; i++) 
    { 
     DataGridView[] dgv = new DataGridView[num]; 

     dgv[i] = new DataGridView(); 
     dgv[i].Name = "dgv" + i.ToString(); 
     dgv[i].MouseDown += onMouseDown; 
     tableLayoutPanel1.Controls.Add(dgv[i]); 
    } 
} 
private void onMouseDown(object sender, MouseEventArgs e) 
{ 
    //var dgv = sender as DataGridView; 
    if (e.Button == MouseButtons.Right) 
    { 
     //perform task ... 
    } 
} 
+0

您也可以使用'MouseUp'事件,而不是'MouseDown'。當您按下按鈕時,「MouseDown」將立即觸發,但在未按下時,「MouseUp」將觸發,就像上下文菜單的行爲一樣。 –