Reputation: 33491
I am selecting data from a Postgres database, and one of these columns is of type TEXT[]
. I bind the data source to a DataGridView
, but those array columns just don't show up (dgData
is a DataGridView
).
dgData.DataSource = getDataTable();
When I now inspect ((DataTable)dgData.DataSource).Columns[15].DataType
, I get the value {Name = "String[]" FullName = "System.String[]"}
, showing me that this is a string array. This column is just gone in the rendering of the DataGrid
.
How can I show that data?
Upvotes: 1
Views: 1244
Reputation: 54433
I don't think a DataGridView
will accept a column of type string[]
.
If it did you could use the CellFormatting
event to create a nicely formatted display version of your data, maybe like so:
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);
}
}
But the Column neither gets created (when using AutoGenerateColumns
) nor gets filled otherwise.
So you should create a readily formatted column. Either in SQL at the database level or later in a Linq line.
Example:
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();
Using my test data:
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);
The result looks like this:
While this means indeed that you need to take care for each field, imo the autogeneration of columns is not as powerful and flexible as one would wish, when it gets down to production code..
Upvotes: 3