Eventos de carregamento de formulário não processados quando o formulário é chamado pela segunda vez
Por que o seguinte não funciona?
Duas formas; primeiro chama o segundo. O segundo formulário possui um DataGridView - ele não possui colunas, são adicionados pelo programa, juntamente com um DataGridViewButtonColumn.
Chamar Form2 pela primeira vez funciona bem. Mas chamando pela segunda vez, os botões não têm texto.
' The first form - has one button, which calls Form2
Pu,blic 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
O código para o segundo formulário é:
' 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