你好我有一个正在制作的项目的工作代码......
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim FolderDlg = FolderBrowserDialog1
'Checks if there is a value to the Selected folder
If FolderDlg.SelectedPath = "" Then
'If no value asks to set one
MsgBox("Please Set a Directory")
FolderDlg.ShowDialog()
If DialogResult.OK Then
Button1.Text = Path.GetFileName(FolderDlg.SelectedPath)
End If
Exit Sub
End If
Process.Start("explorer.exe", FolderDlg.SelectedPath)
End Sub
我希望能够使用“AddNew”按钮创建此代码的副本。我知道如何创建动态按钮,但它们都调用相同的FolderBrowserDialog ..
编辑这是我添加新按钮,创建带有标签的按钮,并使用标签创建FolderBrowserDialogs。
Private Sub AddNew_Click(sender As Object, e As EventArgs) Handles AddNew.Click
Dim count As Integer = FloLay.Controls.OfType(Of Button)().ToList().Count
Dim button As New Button()
count = FloLay.Controls.OfType(Of Button)().ToList().Count
'button.Location = New System.Drawing.Point(150, 25 * count)
'button.Size = New System.Drawing.Size(60, 20)
button.Name = "button_" & (count + 1)
button.Text = "Button_ " & (count + 1)
button.Tag = "Button_" & (count + 1)
AddHandler button.Click, AddressOf Set_Dir
Dim FolderDlg As New FolderBrowserDialog
count = FloLay.Controls.OfType(Of FolderBrowserDialog)().ToList().Count
FolderDlg.Tag = "FolderDlg_" & (count + 1)
FloLay.Controls.Add(button)
End Sub
编辑3 这是我的 NEW NEW 事件处理程序
Private Sub Set_Dir(sender As Object, e As EventArgs)
Dim btn = DirectCast(sender, Button)
If btn.Tag Is Nothing Then
Using fbd As New FolderBrowserDialog
fbd.ShowDialog()
btn.Tag = fbd.SelectedPath
End Using
End If
Dim path = CStr(btn.Tag)
' MsgBox(path)
Process.Start("explorer.exe", path)
End Sub
现在只在应用程序重启或重启后添加Button.Name = GetFileNAme和persistance
编辑4
Private Sub Set_Dir(sender As Object, e As EventArgs)
Dim btn = DirectCast(sender, Button)
If btn.Tag Is Nothing Then
Using fbd As New FolderBrowserDialog
fbd.ShowDialog()
btn.Tag = fbd.SelectedPath
btn.Text = path.GetFileName(fbd.SelectedPath)
End Using
Exit Sub
End If
Dim Folderpath = CStr(btn.Tag)
' MsgBox(Folderpath)
Process.Start("explorer.exe", Folderpath)
End Sub
现在它就像一个魅力!
答案 0 :(得分:0)
您无法创建代码副本。您需要做的是让事件处理程序中的代码根据单击的Button
确定要执行的操作。创建Button
时,可以在其Tag
属性中存储一些数据。在事件处理程序中,sender
参数是对引发事件的对象的引用,即被单击的Button
。然后,您可以从其Tag
属性中获取该数据并使用它。您将使用该数据以适合FolderBrowserDialog
的任何方式配置Button
。 E.g。
创建Button
:
Dim btn As New Button
AddHandler btn.Click, AddressOf ButtonClicked
Me.Controls.Add(btn)
在事件处理程序中:
Dim btn = DirectCast(sender, Button)
If btn.Tag Is Nothing Then
Using fbd As New FolderBrowserDialog
fbd.ShowDialog()
btn.Tag = fbd.SelectedPath
End Using
End If
Dim path = CStr(btn.Tag)
'Use path here.
请注意,Tag
属性的类型为Object
,因此它可以是您想要的任何内容。它可以像Integer
一样简单,也可以像DataSet
一样复杂。您只需将其转换为事件处理程序中的相应类型,然后正常访问所有数据。