【问题标题】:Binding RadioButtonList to nullable varchar workaround? (SelectedValue which is invalid because it does not exist...)将 RadioButtonList 绑定到可为空的 varchar 解决方法? (SelectedValue 无效,因为它不存在......)
【发布时间】:2009-07-24 13:11:45
【问题描述】:

我的数据库表中有一个可为空的 varchar 列。
我通过 objectdatasource 将 gridview 绑定到该表,并有一个 TemplateField,如下所示:

                <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>

如果表中该列中有任何空值,我会收到错误消息:
"'rblRequirementOption' 有一个无效的 SelectedValue,因为它不存在于项目列表中。参数名称:值"

如您所见,我尝试添加一个值为“”的占位符单选按钮来容纳空值,这是处理此错误的常用方法,但在这种情况下,似乎“ " 和 DBNull.Value 不被认为是等效的。

我当然不必在绑定之前将空值转换为长度为零的字符串吗?

更新

实际上,这正确的语法。 (我正在使用默认值替代品,结果搞混了。)

【问题讨论】:

    标签: asp.net


    【解决方案1】:

    你应该使用:

       <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>
    

    【讨论】:

      【解决方案2】:

      我不确定您使用的是什么数据库,但我会首先对可空数据库字段使用 NullIf 语句。

      Select NullIf(RequirementOption, 'None') From ...
      

      这将帮助您避免 Object Reference Not Set to an Instance of an Object 错误,因为您不会从数据存储返回空值。

      【讨论】:

      • 是的,但这会禁用双向数据绑定。
      • 并且本质上与我试图避免的“将空值转换为零长度字符串”相同。
      猜你喜欢
      • 1970-01-01
      • 2012-02-10
      • 2011-11-06
      • 1970-01-01
      • 2018-03-18
      • 1970-01-01
      相关资源
      最近更新 更多