如下
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim newRow As New DataGridViewRow()
Dim newRowCell As New DataGridViewTextBoxCell
newRow.Cells.Add(newRowCell)
newRowCell = New DataGridViewTextBoxCell
newRowCell.Value = Me.TextBox1.Text
newRow.Cells.Add(newRowCell)
DataGridView1.Rows.Add(newRowCell)
End Sub
End Class
运行图如下
根据你的代码,你似乎是在尝试创建一个新的行(newRow
),然后为这个行添加一个新的单元格(newRowCell
)。然后你尝试将这个单元格的值设置为TextBox1
的文本。但是,在你将新的行添加到DataGridView
时,你却添加了新的单元格(newRowCell
)而不是新的行(newRow
)。这可能是问题所在。
你应该改变你的代码,将新的行添加到DataGridView
,而不是新的单元格。以下是修复后的代码:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim newRow As New DataGridViewRow()
Dim newRowCell As New DataGridViewTextBoxCell
newRowCell.Value = Me.TextBox1.Text
newRow.Cells.Add(newRowCell)
DataGridView1.Rows.Add(newRow)
End Sub
End Class
这段代码会在你点击按钮时,为DataGridView1
添加一行,这一行中的单元格包含TextBox1
的文本。