单选按钮列出 NULL 上的选定值

本文关键字:NULL 单选按钮 | 更新日期: 2023-09-27 18:30:50

我在另一篇文章中得到了这个

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

这是正确的语法吗?如果是,有人可以给它的VB版本吗?

SelectedValue='<%# Bind("sex").GetType() == typeof(DBNull) ? null : Bind("sex") %>'

谢谢

编辑:这是该帖子的链接:https://stackoverflow.com/a/5765930/713847

单选按钮列出 NULL 上的选定值

如果使用 value=" 向控件添加第三个不可见的列表项,这将解决问题,因为空值计算将能够与之匹配。您不再需要在 SelectedValue 属性中测试 dbnull。

<asp:RadioButtonList runat=server ID="rd" SelectedValue='<%# Bind("sex")%>'
       <asp:ListItem Text="male" Value="1"></asp:ListItem>
       <asp:ListItem Text="female" Value="2"></asp:ListItem>
       <asp:ListItem Text="" Value="" style="display:none"></asp:ListItem>
</asp:RadioButtonList>

我很确定这行不通,正确的翻译是:

If(TypeOf Bind("sex") Is DBNull, Nothing, Bind("sex"))

为什么不在代码隐藏中以可读的方式执行此操作?

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not IsPostBack Then
        Dim sex = getSexFromStoredProcedure()
        If Not sex Is Nothing Then rd.SelectedValue = sex
    End If
End Sub

编辑:您评论说它在FormView内。我将向您展示如何在DataBound事件中做到这一点。

Private Sub FormView1_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles FormView1.DataBound
    Select Case FormView1.CurrentMode
        Case FormViewMode.ReadOnly
            ' adjust the DataSource accordingly if its not a DataRow '
            Dim row = DirectCast(FormView1.DataItem, DataRow)
            Dim LblSex = DirectCast(FormView1.FindControl("LblSex"), Label)
            Dim sex As String = row.Field(Of String)("Sex")
            LblSex.Text = If(sex Is Nothing, "", sex)
        Case FormViewMode.Edit
            ' adjust the DataSource accordingly if its not a DataRow '
            Dim row As DataRow = DirectCast(FormView1.DataItem, DataRow)
            ' assuming your RadioButtonList is inside the EditItemTemplate '
            Dim RblSex = DirectCast(FormView1.FindControl("RblSex"), RadioButtonList)
            Dim sex As String = row.Field(Of String)("Sex")
            If Not sex Is Nothing Then RblSex.SelectedValue = sex
        Case FormViewMode.Insert
    End Select
End Sub