您使用的语法有点奇怪。有一些重载允许您添加新行并同时设置一个值。
此外,您不能将字符串数组作为单元格的字段。您可以创建一个自定义类,并将它们的列表绑定到 DataGridView,而不是使用 DataTable。这样,您可以拥有一个底层字段,它是一个字符串数组,然后拥有一个公共属性,可以根据需要对其进行格式化,然后将其显示在 DataGridView 中。
以下是如何解决此问题的示例:
Imports System.ComponentModel
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim sales As New BindingList(Of SaleTransaction)
For i As Integer = 1 To 6
sales.Add(New SaleTransaction(i))
Next
' None of this is necessary since the DGV will automatically read the public properties.. '
DataGridView1.AutoGenerateColumns = False
Dim itemsColumn As New DataGridViewTextBoxColumn
itemsColumn.HeaderText = "Items"
itemsColumn.ValueType = GetType(String)
itemsColumn.DataPropertyName = "Items"
DataGridView1.Columns.Add(itemsColumn)
Dim dateColumn As New DataGridViewTextBoxColumn
dateColumn.HeaderText = "Date Sold"
dateColumn.ValueType = GetType(String)
dateColumn.DataPropertyName = "DateSold"
DataGridView1.Columns.Add(dateColumn)
DataGridView1.DataSource = sales
End Sub
Public Class SaleTransaction
Private _items As List(Of String)
Public ReadOnly Property Items As String
Get
Return String.Join(", ", _items)
End Get
End Property
Public Property DateSold As Date
Public Sub New(ByVal itemNumber As Integer)
Me._items = New List(Of String) From {"Pencil" & itemNumber, "Sharpner" & itemNumber}
Me.DateSold = Date.Parse(String.Format("0{0}/0{0}/0{0}", itemNumber))
End Sub
End Class
End Class