我是这里的新手,我做VB.net编程。
我想做一些非常具体的事情,但我不知道如何进行。我有一个ClickEvent,我想用于各种按钮。问题是,我想让每个按钮都更改一个TextBox。我不想在4个单独的ClickEvents中这样做,因为我会重复很多代码。
以下是我想做的:
Private Sub btnOpenDial1_Click(sender As Object, e As EventArgs) Handles btnOpenDial1.Click, btnOpenDial2.Click, btnOpenDial3.Click, btnOpenDial4.Click
Dim UnitLetter As String = Environment.CurrentDirectory.Substring(0, 3)
SaveFileDialog1.InitialDirectory = UnitLetter
SaveFileDialog1.Filter = "rtf file (*.rtf)|*.rtf"
If SaveFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
'name is a TextBox variable that i have at the top of the program
name = SaveFileDialog1.FileName
If (name IsNot Nothing) Then
' I press btnOpenDial1, this textbox changes
txtDoc1.Text = nombre
' I press btnOpenDial2, this textbox changes
txtDoc2.Text = nombre
' I press btnOpenDial3, this textbox changes
txtDoc3.Text = nombre
' I press btnOpenDial4, this textbox changes
txtDoc4.Text = nombre
End If
Catch Ex As Exception
MessageBox.Show("No se ha podido grabar el archivo: " & Ex.Message)
End Try
End If
End Sub
我希望我解释得足够好。英语不是我的主要语言。我只是不想在我的程序中重复更多的代码。提前感谢
您可以使用这样的东西:
您可以对所有按钮使用一种ClickEventHandler
方法(与EventArgs
类型相同的按钮可能因类型不同而不同(。单击每个按钮的Event
,您可以从其名称中检测到它(如代码所示(。此时,当您检测到被单击的按钮时,您可以运行与该按钮相关的特定代码。
希望是你想要的
Private Sub btnOpenDial1_Click(sender As Object, e As EventArgs) Handles btnOpenDial1.Click,
btnOpenDial2.Click,
btnOpenDial3.Click,
btnOpenDial4.Click
Dim pressedButton As Control = CType(sender, Control)
Dim UnitLetter As String = Environment.CurrentDirectory.Substring(0, 3)
SaveFileDialog1.InitialDirectory = UnitLetter
SaveFileDialog1.Filter = "rtf file (*.rtf)|*.rtf"
If SaveFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
'name is a TextBox variable that i have at the top of the program
Name = SaveFileDialog1.FileName
If (Name IsNot Nothing) Then
Select Case pressedButton.Name
Case "btnOpenDial1" : txtDoc1.Text = nombre
Case "btnOpenDial2" : txtDoc2.Text = nombre
Case "btnOpenDial3" : txtDoc3.Text = nombre
Case "btnOpenDial4" : txtDoc4.Text = nombre
End Select
End If
Catch Ex As Exception
MessageBox.Show("No se ha podido grabar el archivo: " & Ex.Message)
End Try
End If
End Sub