Formularladeereignisse werden nicht verarbeitet, wenn das Formular zum zweiten Mal aufgerufen wird
Warum funktioniert das Folgende nicht?
Zwei Formen; der erste ruft den zweiten an. Auf dem zweiten Formular befindet sich eine DataGridView. Sie enthält keine Spalten. Sie werden vom Programm zusammen mit einer DataGridViewButtonColumn hinzugefügt.
Der erste Aufruf von Form2 funktioniert einwandfrei. Beim zweiten Aufruf haben die Schaltflächen jedoch keinen Text.
' 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
Code für das zweite Formular ist:
' 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