Over the ASP.Net forums where I frequently participate, a member asked the difference between using single quotes and double quotes in a databinding expression. So I thought of sharing the answer that I have provided on that thread as a reference to others.
Here's the actual question of the user:
I have always been wondering what can be the reason behind the following?
<asp:GridView runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField runat="server" Value="<%#Eval("ColumnName")%>" />
</ItemTemplate>
<asp:TemplateField>
</Columns>
</asp:GridView>
When written with " " always gives error The server tag is not well formed.
Whereas if we write it in single quotes Value = '<%#Eval("ColumnName")%>' , it is accepted!!!
Why is this so? Googling didnt turn out to be useful for me to find ut reson behind this.
Any ways got such questions in mind before n whetherhe/she got the answer to the same?!?!
Basically, the difference is when you use double quotes [""] in your databinding statement and assign it to a server control property like Text or Value, the HTML parser will interpret the expression as a multiple strings. So if you'll have this line below:
Value='<%# Eval("ColumnName") %>'
The html parser thinks that expression "<%# Eval(" is a string by itself. So based on the above expression, the html parser is looking for two strings which are the: (1)"<%# Eval(" ColumnName (2)") %>" . That's why you'll get the error The server tag is not well formed because using double qoutes is not allowed for inline databinding because this messes up your html element format. To avoid that error then you'll need to use single quotes in which the html parser will be able to realize that there is another nested string inside the outer sting.
I hope someone find this useful!
Technorati Tags:
ASP.NET,
General