Search code examples
asp.netlinqlinq-to-sqldatagridview

Using custom column names in LINQ


I'm binding a query to a WinForms DataGridView. I want the column headers to have spaces when needed. For example, I would want a column header to be First Name instead of FirstName.

How do you create your own custom column names in LINQ?

For example:

Dim query = From u In db.Users _
            Select u.FirstName AS 'First Name'

Solution

  • I solved my own problem but all of your answers were very helpful and pointed me in the right direction.

    In my LINQ query, if a column name had more than one word I would separate the words with an underscore:

    Dim query = From u In Users _
                Select First_Name = u.FirstName
    

    Then, within the Paint method of the DataGridView, I replaced all underscores within the header with a space:

    Private Sub DataGridView1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles DataGridView1.Paint
        For Each c As DataGridViewColumn In DataGridView1.Columns
            c.HeaderText = c.HeaderText.Replace("_", " ")
        Next
    End Sub