0

我正在设计一个带有datagridview的winform。
我正在为该 datagridview 分配一个数据表。

DataTable dt = new DataTable();
dt.Columns.Add("items", typeof(string[]));
dt.Columns.Add("dateSold", typeof(string));

for (int i = 0; i < 6; i++)
{
    dt.Rows.Add(dt.NewRow());
    dt.Rows[i]["items"] = new string[] { "pencil" + i, "sharpner" + i };
    dt.Rows[i]["dateSold"] = "0" + i + "/0" + i + "/0" + i;
}
dataGridView1.DataSource = dt;

列项是一个字符串数组。我想在网格的一个列中显示这个数组。但是通过简单地将数据表分配为 datagridview 的数据源并没有帮助。

4

1 回答 1

0

您使用的语法有点奇怪。有一些重载允许您添加新行并同时设置一个值。

此外,您不能将字符串数组作为单元格的字段。您可以创建一个自定义类,并将它们的列表绑定到 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
于 2012-04-10T19:45:22.247 回答