Los eventos de carga de formularios no se procesan cuando se llama al formulario por segunda vez
¿Por qué no funciona lo siguiente?
Dos formas; primero llama al segundo. El segundo formulario tiene un DataGridView en él: no tiene columnas, el programa los agrega, junto con un DataGridViewButtonColumn.
Llamar a Form2 la primera vez funciona bien. Pero llamándolo por segunda vez, los botones no tienen ningún 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
El código para el segundo formulario es:
' 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