LINQ: custom column names LINQ: custom column names asp.net asp.net

LINQ: custom column names


As CQ states, you can't have a space for the field name, you can return new columns however.

var query = from u in db.Users            select new            {                FirstName = u.FirstName,                LastName = u.LastName,                FullName = u.FirstName + " " + u.LastName            };

Then you can bind to the variable query from above or loop through it whatever....

foreach (var u in query){   // Full name will be available now    Debug.Print(u.FullName); }

If you wanted to rename the columns, you could, but spaces wouldn't be allowed.

var query = from u in db.Users            select new            {                First = u.FirstName,                Last = u.LastName            };

Would rename the FirstName to First and LastName to Last.


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("_", " ")    NextEnd Sub


If you want to change the header text, you can set that in the GridView definition...

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">    <Columns>        <asp:BoundField DataField="FirstName" HeaderText="First Name" />    </Columns></asp:GridView>

In the code behind you can bind to the users and it will set the header to First Name.

protected void Page_Load(object sender, EventArgs e){     // initialize db datacontext     var query = from u in db.Users                 select u;     GridView1.DataSource = query;     GridView1.DataBind();}