by Tim
27. August 2010 16:39
I've kind of got into the habit of using a Repeater every time I want to display and manipulate data. However, I thought I'd play around with the GridView and DetailsView and create a simple bookmarks application. I used a HyperLinkField and set the DataNavigateUrlFields and DataTextField to the Url field in my database table. I needed to be able to edit this field so I decided to make it a template field. I added a text box to the EditItemTemplate with the text set to:
<%# Eval("Url") %>
When I tried to edit the field though, I would get an error:
Cannot insert the value NULL into column 'Url'...
This is how the complete source of the TemplateField looked:
<asp:TemplateField HeaderText="Url" SortExpression="Url">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("Url") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# Eval("Url") %>' Target="_blank" Text='<%# Eval("Url") %>'>
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
The reason for the error was that I was using Eval and not Bind. The Eval function is used to define one-way (read-only) binding. The Bind function is used for two-way (updatable) binding. In addition to calling Eval and Bind methods to perform data binding in a data-binding expression, you can call any publicly scoped code within the <%# and %> delimiters to execute that code and return a value during page processing. I was used to using my own publicly scoped code so was a bit unfamiliar with these two functions.
More info. on this topic at MSDN