I have a GridView bound to some Entity Datasource. Editing is enabled. Entity shown in GridView is associated with another entity. Let’s say I’m displaying Machines which are creating Products (none or one product type per machine). I’m displaying name of the product in gridview with
<ItemTemplate>
<asp:Label ID="Label1" runat="server"
Text='<%# ((Machine)Container.DataItem).Product == null ? "-" : ((Machine)Container.DataItem).Product.Name %>'>
</asp:Label>
</ItemTemplate>
which works well. Now I want to be able to edit associated product in EditItemTemplate. So I added
<EditItemTemplate>
<asp:DropDownList runat="server" ID="ddProducts" DataSourceID="dsProducts"
DataTextField="Name" DataValueField="ProductID"
SelectedValue='<%# Bind("Product.ProductID") %>'
AppendDataBoundItems="true">
<asp:ListItem Text="" Value="0"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
It’s not working because when machine doesn’t have a product associated there is no matching SelectedValue and anyway Product is null. I added empty item to DropDownList which should be selected when machine has no product. And also if I edit machine with product and choose this item, column should be nulled.
How can I achieve this?
I got it to work now.
GridViewautomatically converts nulls to empty strings, so the problem was not with binding but with the special item I added for null values.Changing
to
solved the problem instantly…