34

What is the best way to use multiple EVAL fields in a GridView ItemTemplate?

Looking to have some control over formatting for appearance as well as setting up hyperlinks/javascript etc.

4 Answers 4

64

Even clearer, IMO, is:

<%# String.Format("{0} - {1}", Eval("Name1"), Eval("Name2")) %>
1
  • Suppose Name1 is a string say "Obama....." How to get only First 3 Chars using Format string...? Mar 18, 2014 at 9:53
6

I had previously used this (bad, I know):

<%# Eval("Name1", "{0} - ")%> <%#Eval("Name2")%>

Result = 'John - Smith'

But just discovered that I can also put TWO (or more) Evals in the same data-bound group:

<%#Eval("Name1") & " - " & Eval("Name2")%>

Result = 'John - Smith'

Or

<%# "First Name - " & Eval("Name1") & ", Last Name - " & Eval("Name2")%>  

Result = 'First Name - John, Last Name - Smith'

6

Eval and Bind both suck.
Why get the property through reflection? You can access it directly like this:

((MyObject)Container.DataItem).MyProperty

It's not like the object is unknown to you at runtime. That's my two cents, anyhow.

1
  • Totally like this method, it's clean.
    – bryan
    Jul 11, 2011 at 0:14
3

I have a easiest way to do this same thing...

<asp:Label ID="lblName" runat="server" Text='<%#Eval("FirstName").ToString() +", "+ Eval("LastName").ToString() %>'></asp:Label>

.

<%#Eval("FirstName").ToString() +", "+ Eval("LastName").ToString() %>

Here both objects are converted into string the concatenate them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.