2012-04-12 72 views
0

我在另一篇文章單選按鈕列表中選擇值在NULL

<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

+0

什麼是你想才達到 – 2012-04-12 19:48:51

+1

'如果(typeof運算綁定(「性」)是DBNull的,沒什麼,綁定(「性」))'但是我不認爲這工作。 – 2012-04-12 19:50:36

+0

如果我的存儲過程返回null爲「性別」比沒有被選中,否則將選擇「男性」/「女性」基於從綁定返回的值(「性別」) – SZT 2012-04-12 19:51:51

回答

1

我相當肯定,這是行不通的,正確的翻譯是:

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

你是對的,它沒有工作我的radioButtonList在formview中,所以我只想使用FormView的databound方法。顯然,如果我不這樣做Formview的ItemTemplate不會顯示:@ – SZT 2012-04-12 20:04:50

+1

@ user713847:看看我編輯的答案。 – 2012-04-12 20:22:37

2

如果添加第三個,看不見的,列表項,其中值控制=「」這將避開這個問題作爲空評估將能夠匹配到它....您不再需要在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>