1
votes

I need to display a column called Full Name in a DataGridView, but the DataSource (datatable) does not have a FullName column. It only has FirstName and LastName columns. I'm setting up my DataGridView like this:

Dim column As DataGridViewColumn = New DataGridViewTextBoxColumn()
column.DataPropertyName = "?" //Need FirstName + " " + LastName
column.Name = "FullName"
dgv.Columns.Add(column)

How can I set the DataPropertyName to use data from both the FirstName and LastName columns in the datatable.?

Thanks.

2
Steve's answer is very nice - since you already have a datatable that is almost certainly the way to go. For completeness though, it is worth noting that you can have calculated columns in the grid itself stackoverflow.com/questions/6097370/… - David Hall

2 Answers

4
votes

Using another approach. Add a calculated column to your datatable.

Dim dc as DataColumn = dt.Columns.Add("FullName", System.Type.GetType("System.String"))
dc.Expression = "FirstName + ' ' + LastName"

where dt is the datatable that you set as DataSource of your DataGridView.

The rules for the expression syntax used in calculated columns could be found at this link on MSDN.
The very same rules apply also to another very useful method: the DataTable.Select(filterExpression) method

1
votes

I don't think that's how DataPropertyName works. http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcolumn.datapropertyname.aspx

Do this on the database side of things instead. In your select (SQL Server syntax here), do a FirstName + " " + LastName as FullName and you'll get a FullName column back instead of the two columns.

If you don't have access to the SQL side, you can manipulate the DataTable and create your own FullName column in code. I'd imagine some LINQ and/or looping should do the trick.