0

我是新来的,我做 VB.net 编程。

我想做一些非常具体的事情,但我不知道如何接近它。我有一个想要用于各种按钮的 ClickEvent。问题是我想让每个按钮更改一个文本框。我不想在 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

我希望我解释得足够好。英语不是我的主要语言。我只是不想在我的程序上重复更多代码。提前致谢

4

1 回答 1

1

你可以使用这样的东西:

您可以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
于 2020-11-21T12:45:10.753 回答