2016-04-24 202 views
1

好的,這是一個有點棘手的解釋。如何知道winform c#中點擊了哪個按鈕?

我正在研究一個基本的時間表格。

我有7個按鈕,名爲btnMonTimebtnTueTime依此類推,直到btnSunTime根據星期幾。現在,每按一次按鈕,彈出一個窗口(winform)打開,讓用戶通過dateTimePicker控件選擇一定的時間。時間被解析爲一個字符串並存儲。彈出窗口中有一個接受按鈕,當按下該按鈕時,彈出窗口關閉,並在特定日期旁邊顯示標註時間的標籤。

Image where popup comes up when Time beside Monday is clicked

`Image where label with the time has to be places beside the particular day whose Time button was pressed

現在我知道該怎麼做了一個特殊的日子,但事情是,我有一個單一的功能做這個標籤製作。但是,如何知道點擊哪個時間按鈕將其放置在正確的位置?

這是我能想出的代碼:

private void btnAccept_Click(object sender, EventArgs e) 
{ 
     formPopup.time = timePicker.Value.ToShortTimeString(); 
     //label1.Text = formPopup.time; 

     Label newLabel = new Label(); 
     newLabel.Text = formPopup.time; 
     newLabel.Location = new System.Drawing.Point(205 + (100 * formTimeTable.CMonTime), 78); 
     formTimeTable.CMonTime++; 
     newLabel.Size = new System.Drawing.Size(100, 25); 
     newLabel.ForeColor = System.Drawing.Color.White; 
     thisParent.Controls.Add(newLabel); 

     this.Close(); 
} 

這是哪個地方的標籤,在正確的地方接受按鈕單擊處理程序。而變量CMonTime記錄按下特定按鈕的次數。

public static int CMonTime = 0; 
private void btnMonTime_Click(object sender, EventArgs e) 
{ 
    formPopup f2 = new formPopup(); 
    f2.thisParent = this; 
    f2.Show();  
} 

這就是星期一的時間按鈕點擊處理程序中發生的情況。

但是我怎麼能知道哪天的時間按鈕實際上被點擊以正確放置時間戳標籤?

就像星期二的時間按鈕被點擊一樣,時間戳應該顯示在星期二的時間按鈕旁邊。

我試圖儘可能清楚。

在此先感謝。

回答

0

sender是引發事件的對象。在你的情況下,它將是用戶點擊的按鈕。

+0

你能詳細談談那一點嗎? –

+0

你不遵循哪一點? – yaakov

2

您可以通過將sender參數強制轉換爲Button控件來獲取單擊的按鈕。 使用按鈕的位置作爲一個參數爲你的表單爲例構造

private void btnMonTime_Click(object sender, EventArgs e) 
{ 
    var button = (Button)sender; 
    formPopup f2 = new formPopup(button.Location); 
    f2.thisParent = this; 
    f2.Show();  
} 

表單爲例

Point _buttonLocation; 

public frmPopup(Point buttonLocation) 
{ 
    _buttonLocation = buttonLocation; 
} 

然後使用該按鈕的位置來設置標籤的位置

private void btnAccept_Click(object sender, EventArgs e) 
{ 
    formPopup.time = timePicker.Value.ToShortTimeString(); 

    Label newLabel = new Label(); 
    newLabel.Text = formPopup.time; 
    newLabel.Location = new Point(_buttonLocation.X + 100, _buttonLocation.Y); 

    formTimeTable.CMonTime++; 
    newLabel.Size = new System.Drawing.Size(100, 25); 
    newLabel.ForeColor = System.Drawing.Color.White; 
    thisParent.Controls.Add(newLabel); 

    this.Close(); 
} 
0

因爲控制這些組合重複,創建一個包含所需按鈕和標籤的用戶控件可能會更容易。把UserControl想象成一個由少數幾個控件組成的小型表單,然後根據需要將它放置在表單上。它有自己的事件處理程序。這樣在技術上只有一個按鈕(不是七個)和一個事件處理程序。然後,您可以將該UserControl放置在您的表單上七次。

還有其他一些方法可以避免重複代碼,例如有一個事件處理程序並將其分配給所有七個按鈕的點擊事件。但是,如果你想編輯按鈕的佈局,UserControl會節省你的時間。你不想這樣做七次。

要嘗試一下:

  • 添加>新建項目>用戶控制。你會得到看起來像一個新的形式。以與將表單添加到控件相同的方式添加一些控件。然後使用名稱保存(僅作爲示例)MyUserControl.cs
  • 構建項目。
  • 工具箱中將出現一個新的工具箱選項卡,並且您的控件將在那裏。
  • 將控件拖到表單上,就像其他任何控件一樣。

More info on creating user controls

相關問題