为什么以下不起作用?
两种形式;先打电话给第二个。第二个表单上有一个DataGridView - 它没有列,它们是由程序添加的,还有一个DataGridViewButtonColumn。
第一次调用Form2工作正常。但是第二次调用它时,按钮没有任何文本。
' The first form - has one button, which calls Form2
Public Class Form1
Friend fruit As New List(Of Fruit)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
fruit.Add(New Fruit("Apple", "Red"))
fruit.Add(New Fruit("Orange", "Orange"))
fruit.Add(New Fruit("Banana", "Yellow"))
fruit.Add(New Fruit("Melon", "Red"))
fruit.Add(New Fruit("Pear", "Green"))
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Form2.ShowDialog()
End Sub
End Class
Public Class Fruit
Public Property name As String
Public Property colour As String
Public Sub New(newName As String, newColour As String)
name = newName
colour = newColour
End Sub
End Class
第二种形式的代码是:
' Form2 has a button which closes the form, and a DataGridView
Public Class Form2
Dim dataGridViewButtonColumn1 As DataGridViewButtonColumn
Dim setupAlready As Boolean = False
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
dataGridViewButtonColumn1 = New DataGridViewButtonColumn
DataGridView1.DataSource = Form1.fruit
With dataGridViewButtonColumn1
.Name = "ButtonCol"
.UseColumnTextForButtonValue = False
End With
If Not setupAlready Then
DataGridView1.Columns.Add(dataGridViewButtonColumn1)
End If
For i As Integer = 0 To 4
DataGridView1.Rows(i).Cells("ButtonCol").Value = "Hello"
Next
setupAlready = True
End Sub
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) _
Handles DataGridView1.CellContentClick
Debug.Print(String.Format("Col={0}, Row={1}, ColName={2}", e.ColumnIndex, e.RowIndex, DataGridView1.Columns(e.ColumnIndex).Name))
If (DataGridView1.Rows.Item(e.RowIndex).Cells("ButtonCol").Value Is "Hello") Then
DataGridView1.Rows.Item(e.RowIndex).Cells("ButtonCol").Value = "GoodBye"
DataGridView1.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.LightGreen
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.Close()
End Sub
End Class
答案 0 :(得分:3)
我认为你有几个导致这种情况的趋同。首先,表单是类,应该明确地实例化。而不是Form2.ShowDialog()
执行此操作:
Using frm As New Form2 ' create instance
frm.ShowDialog
' do something
End Using ' dialogs are also a resource
普通表格不需要 Using
/ .Dispose
,因为当你关闭它们时,它们会被处理掉。对话框不是这样,因为我们异常地隐藏它们以便我们可以从中获取信息。
接下来,只有在您显示表单时才会调用Form_Load事件。请参阅MSDN:Occurs before a form is displayed for the first time.
因此,通过重用非处置的Form2
,不会调用Load事件,并且不会执行Load事件中的代码。如果您处置并创建新的表单实例,它应该可以正常工作。顺便说一句,这适用于所有形式,而不仅仅是对话框。