Reputation: 5865
I have a nullable varchar column in a table in my database.
I am binding a gridview to this table via an objectdatasource and have a TemplateField like so:
<asp:RadioButtonList ID="rblRequirementOption" RepeatDirection="Horizontal" runat="server" RepeatLayout="Flow"
SelectedValue='<%#Bind("RequirementOption")%>'>
<asp:ListItem Value="" Text="" style="display: none" />
<asp:ListItem Value="Need" Text="Need"></asp:ListItem>
<asp:ListItem Value="Do Not Use" Text="Do Not Use"></asp:ListItem>
</asp:RadioButtonList>
If there are any null values in that column in the table, I get the error:
"'rblRequirementOption' has a SelectedValue which is invalid because it does not exist in the list of items. Parameter name: value"
So as you can see, I have tried to add a placeholder radio button with a value of "" to accomodate the null values, which is the commonly advised method to handle this error, but in this case, it seems that "" and DBNull.Value are not considered equivalent.
Surely I don't have to convert nulls to a zero length string before binding do I?
Actually, this is the correct syntax to do it. (I was futzing around with a default value substitute and got all mixed up.)
Upvotes: 1
Views: 4007
Reputation: 21
you shoud use:
<asp:RadioButtonList runat=server ID="rd" SelectedValue='<%# Bind("sex").GetType() == typeof(DBNull) ? null : Bind("sex") %>'
<asp:ListItem Text="male" Value="1"></asp:ListItem>
<asp:ListItem Text="female" Value="2"></asp:ListItem>
</asp:RadioButtonList>
Upvotes: 1
Reputation: 73564
I'm not sure what DB you're using, but I'd start by using the NullIf statement for the nullable database fields.
Select NullIf(RequirementOption, 'None') From ...
That will help you avoid the Object Reference Not Set to an Instance of an Object errors because you won't be returning nulls from the data store.
Upvotes: 0