将数组字符串绑定到datagridview的列

时间:2012-04-10 19:05:03

标签: .net winforms datagridview datatable

我正在设计一个具有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;

列项是一个字符串数组。我想在网格的一个coloum中显示这个数组。 但是,通过简单地将数据表分配为datagridview的数据源无济于事。

1 个答案:

答案 0 :(得分:0)

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

此外,您不能将字符串数组作为单元格的字段。您可以创建自定义类,而不是使用DataTable,并将它们的列表绑定到DataGridView。这样你就可以有一个基础字段,它是一个字符串数组,然后有一个公共属性,可以根据需要格式化它们,然后在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