简体   繁体   中英

Radiobuttonlist selected value on NULL

I got this in another post

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

Is this a correct syntax?? If yes can someone please give the VB version of it??

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

Thanks

EDIT: Here's the link to that post: https://stackoverflow.com/a/5765930/713847

If you add a third, invisible, listitem to the control with a value="" this will get round the problem as the null evaluation will be able to match to it....you no longer need to test for dbnull in the selectedvalue attribute.

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

I'm fairly sure that this won't work, the correct translation is:

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

Why not doing it in a readable way in codebehind?

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

Edit : You've commented that it's inside a FormView . I'll show you how to do it in the DataBound event.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM