如何在DataGridView中显示数组列

时间:2019-05-23 14:06:58

标签: c# datagridview datatable datasource

我正在从Postgres数据库中选择数据,这些列之一为TEXT[]类型。我将数据源绑定到DataGridView,但这些数组列只是不显示(dgDataDataGridView)。

dgData.DataSource = getDataTable();

当我现在检查((DataTable)dgData.DataSource).Columns[15].DataType时,我得到的值{Name = "String[]" FullName = "System.String[]"}告诉我这是一个字符串数组。此列仅在DataGrid的呈现中消失。

如何显示这些数据?

1 个答案:

答案 0 :(得分:0)

我认为DataGridView不会接受类型为string[]的列。

如果,您可以使用CellFormatting事件来创建数据的格式良好的显示版本,也许是这样的:

private void DataGridView1_CellFormatting(object sender,
                                          DataGridViewCellFormattingEventArgs e)
{
    if (e.ColumnIndex == yourIndexOrName1 && e.Value != null)
    {
        var s = e.Value as string[];
        e.Value = String.Join(", ", s);
    }
}

但是该列既不会创建(使用AutoGenerateColumns时),也不会被填充。

因此,您应该创建一个格式简单的列。在数据库级别的 SQL 中或更高版本的 Linq 行中。

示例:

var dt_ = dt.Rows.Cast<DataRow>().Select(x => new {
    f1 = x.Field<string>(0),
    f2 = x.Field<string[]>(1).Aggregate((i, j) => i + ", " + j),
    f3 = x.Field<int>(2)
});

dataGridView1.DataSource = dt_.ToList();

使用我的测试数据:

DataTable dt = new DataTable();
dt.Columns.Add("col1", typeof(string));
dt.Columns.Add("col2", typeof(string[]));
dt.Columns.Add("col3", typeof(int));

var row = dt.NewRow();
row.SetField<string>("col1",  "A");
row.SetField<string[]>("col2", new string[] { "abc", "xyz", "123" });
row.SetField<int>("col3", 23 );
dt.Rows.Add(row);
row = dt.NewRow();
row.SetField<string>("col1", "B");
row.SetField<string[]>("col2", new string[] { "a-b-c", "x+y+z", "1:2:3" });
row.SetField<int>("col3", 42);
dt.Rows.Add(row);

结果如下:

enter image description here

虽然这确实意味着您需要注意每个字段,但在生成代码时,自动生成列的功能却不如人们所希望的强大和灵活。

相关问题