2013-07-27 52 views
1

我有以下步驟:轉私子到功能

Private Sub btnRptEmployeePayToMarket_MouseDown(ByValsender As Object, ByVal myButton As System.Windows.Forms.MouseEventArgs) Handles btnRptEmployeePayToMarket.MouseDown 

    Static Toggle As Boolean 

    If myButton.Button = MouseButtons.Right Then 

     If Toggle Then 

      descForm.Hide() 

     Else 

      descForm.lblReportTitle.Text = "Ranges to Market" 
      descForm.txtButtonDescription.Text = "Learn how you are currently paying specific departments or jobs compared to market. " 
      descForm.Show() 

     End If 

    End If 
    Toggle = Not Toggle 

End Sub 

因爲我有9個按鍵,將執行相同的動作,但只是改變descForm.lblReportTitle和descForm.txtButtonDescription文本,如何我能完成這個嗎?

我想將sub變成一個函數,但我不知道該如何實現。

+0

究竟是你想實現什麼目標?處理程序總是Subs。 – Neolisk

回答

1

首先,您需要離開切換標誌,以便知道某個特定按鈕是否切換。

要做到這一點,我保留一個布爾對象字典,鍵入按鈕的名稱。當常用方法執行時,它會添加標誌(如果它尚不存在),使用它來確定適當的行爲,然後切換它。

這裏是你的代碼有了這個邏輯重寫:

Private m_cToggleFlags As New System.Collections.Generic.Dictionary(Of String, Boolean) 

Private Sub btnRptEmployeePayToMarket_MouseDown(ByVal sender As Object, ByVal myButton As System.Windows.Forms.MouseEventArgs) Handles btnRptEmployeePayToMarket.MouseDown 

    ToggleButton(DirectCast(sender, Control).Name, "Ranges to Market", "Learn how you are currently paying specific departments or jobs compared to market.") 
End Sub 

Private Sub ToggleButton(sButtonName As String, sReportTitle As String, sButtonDescription As String) 

    If Not m_cToggleFlags.ContainsKey(sButtonName) Then 
     m_cToggleFlags.Add(sButtonName, False) 
    End If 

    If m_cToggleFlags(sButtonName) 
     descForm.Hide() 
    Else 
     descForm.lblReportTitle.Text = sReportTitle 
     descForm.txtButtonDescription.Text = sButtonDescription 
     descForm.Show() 
    End If 

    m_cToggleFlags(sButtonName) = Not m_cToggleFlags(sButtonName) 
End Sub 
+0

謝謝。它實際上解決了我在使用我的代碼時遇到的其他兩個問題。我對編程非常陌生,所以我對我的代碼完成了很多感到驕傲,直到我看到你的代碼並且謙虛爲止。 :-) –

1

您可以添加處理程序到這個子。

Private Sub btnRptEmployeePayToMarket_MouseDown(ByValsender As Object, ByVal myButton As System.Windows.Forms.MouseEventArgs) Handles btnRptEmployeePayToMarket.MouseDown, btnAnotherone.MouseDown, etc...