【问题标题】:How to show array columns in DataGridView如何在 DataGridView 中显示数组列
【发布时间】:2019-10-10 03:18:21
【问题描述】:

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

dgData.DataSource = getDataTable();

当我现在检查((DataTable)dgData.DataSource).Columns[15].DataType 时,我得到了值{Name = "String[]" FullName = "System.String[]"},表明这是一个字符串数组。这个专栏刚刚在DataGrid的渲染中消失了。

如何显示这些数据?

【问题讨论】:

  • 你期待什么?第一个字符串?调试器是否显示单元格值的可靠数据?
  • @TaW 好吧,我确实期待一个逗号分隔的列表,或者psql 给我的一些渲染。但现在想来,我真的不知道会发生什么。
  • getDataTable 返回数据表?您需要检查您在 DataTable 中为该列获得的确切值。在将其绑定到数据网格视图之前,您需要将其转换为逗号分隔值。自动列绑定不会区别对待数据。
  • @ChetanRanpariya:“在将其绑定到数据网格视图之前,您需要将其转换为逗号分隔值。”我该怎么做?

标签: c# datagridview datatable datasource


【解决方案1】:

我认为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);

结果如下:

虽然这确实意味着您需要注意每个字段,但当涉及到生产代码时,imo 列的自动生成并不像人们希望的那样强大和灵活。..

【讨论】:

  • 谢谢,我想我必须以其他方式修复它。不过有趣的是,我还有一个hstore 列,它映射到IDictionary,它在DataGridView 中呈现为(Collection)
  • 嗯,很有趣;会显示什么?键,键和值?还是有 ToString 方法?
  • 字面意思是(Collection)
  • 好的,当缺少正确的 ToString 方法时,(类名)是默认输出。这意味着该列正在被填充,这意味着您可以使用 CellFormatting 事件将数据转换为可读版本..
猜你喜欢
  • 2011-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多