我在 buttonNamesAndFormNames 方法上收到 '}'预期 错误。我似乎可以弄清楚为什么它会抛出错误,因为您可以在方法的末尾清楚地看到它。我已经包含了其他方法,因为我试图将动态创建的按钮重定向到我的 DocumentUnderstand 表单。我希望侧栏中的这些按钮重定向到 VB.NET 中的所有不同表单。我尝试过“清理”和“重建”,但错误仍然存在。非常感谢任何帮助。
' Define an array with button names and their corresponding form names
Private buttonNamesAndFormNames() As (buttonName As String, formName As String) = {
("Document understanding", "DocUnderstand.vb"),
("Button 2", "Form2"),
("Button 3", "Form3"),
("Button 4", "Form4"),
("Button 5", "Form5"),
("Button 6", "Form6")
' Add more button names and corresponding form names as needed
}
Private Sub SideMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
InitializeDynamicControls()
End Sub
Private Sub InitializeDynamicControls()
' Add buttons dynamically based on the buttonNamesAndFormNames array
For Each pair In buttonNamesAndFormNames
Dim button As New Button()
button.Text = pair.buttonName
button.Dock = DockStyle.Top
AddHandler button.Click, AddressOf OpenForm
Panel1.Controls.Add(button)
Next
End Sub
Private Sub OpenForm(sender As Object, e As EventArgs)
' Handle button click event
Dim button As Button = DirectCast(sender, Button)
Dim index As Integer = -1
' Find the index of the clicked button in the buttonNamesAndFormNames array
For i As Integer = 0 To buttonNamesAndFormNames.Length - 1
If buttonNamesAndFormNames(i).buttonName = button.Text Then
index = i
Exit For
End If
Next
' Open the corresponding form based on the index
If index >= 0 AndAlso index < buttonNamesAndFormNames.Length Then
Dim formName As String = buttonNamesAndFormNames(index).formName
' Assuming that the form files are in the same namespace as SideBar
If Not String.IsNullOrEmpty(formName) Then
Dim formInstance As Form = CType(Activator.CreateInstance(Type.GetType(formName)), Form)
formInstance.Show()
Else
MessageBox.Show("Invalid form name or form not found.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
Else
MessageBox.Show("Invalid button index.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
End Sub
您一直将
buttonNamesAndFormNames
作为问题中的一种方法。它不是。这是一个领域。这意味着大括号之间的内容是单个值,而不是多行代码。您不能在值的中间添加注释。您所做的相当于:
Private numbers As Integer() = {
1,
2,
3
'Blah blah
}
这和这个完全一样:
Private numbers As Integer() = {1, 2, 3 'Blah blah}
这显然不是有效的代码。
将该评论从你的价值中剔除,并将其放在评论有效的地方。