What is the use of Eval()
in ASP.NET?
3 Answers
While binding a databound control, you can evaluate a field of the row in your data source with eval() function.
For example you can add a column to your gridview like that :
<asp:BoundField DataField="YourFieldName" />
And alternatively, this is the way with eval :
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lbl" runat="server" Text='<%# Eval("YourFieldName") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
It seems a little bit complex, but it's flexible, because you can set any property of the control with the eval() function :
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl='<%# "ShowDetails.aspx?id="+Eval("Id") %>'
Text='<%# Eval("Text", "{0}") %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>

- 47,715
- 17
- 91
- 122
-
10I wish I had a dollar for every time I forget to use single quotes on the tag attribute when I used double quotes in Eval – Matthew Lock May 09 '13 at 05:02
-
1Sorry I don't understand ```Text='<%# Eval("Text", "{0}") %>'``` How does it work? – May 25 '18 at 21:56
-
Eval is used to bind to an UI item that is setup to be read-only (eg: a label or a read-only text box), i.e., Eval is used for one way binding - for reading from a database into a UI field.
It is generally used for late-bound data (not known from start) and usually bound to the smallest part of the data-bound control that contains a whole record. The Eval method takes the name of a data field and returns a string containing the value of that field from the current record in the data source. You can supply an optional second parameter to specify a format for the returned string. The string format parameter uses the syntax defined for the Format method of the String class.

- 5,841
- 5
- 27
- 43
-
4Eval method is to receive data and bind to UI control. But how the data has been sent? if there is a eval method "Text="<%#Eval("data1")%>"", how the data1 to be sent? – king yau Sep 15 '16 at 04:42
IrishChieftain didn't really address the question, so here's my take:
eval() is supposed to be used for data that is not known at run time. Whether that be user input (dangerous) or other sources.

- 687
- 1
- 5
- 13