Tip/Trick:ASP.NET2.0DealwithDBNullvaluewhenbind 

來源:互聯網
上載者:User

對於輸入值二選一這種情況(比如是、否,男、女),UI上最符合邏輯得輸入控制項應該時單選按紐組(radio),當然也可以用下拉式清單方塊(select),但我覺得多選一的時候用它才合適。在ASP.NET 2.0裡,使用單選按紐組對應的伺服器控制項就是RadioButtonList。綁定資料時與其他ListControl一樣設定其SelectedValue屬性SelectedValue='<%# Bind("FiledlNameInDB") %>'(這裡談的是直接綁定資料庫,通常時通過Datasrouce控制項)。但這時有個問題,當資料庫中該欄位允許為空白,而使用者確實輸入了空值時,當執行綁定時RadioButtonList就會報錯,因為在值列表中找不到對應的一個空值。DripdownList也有這個問題,但Dropdownlist可以簡單通過加入一個具有空值的Listitem來解決這個問題,如<asp:ListItem Value="">--None--</asp:ListItem>。對於RadioButtonList嘗試了幾種辦法,沒有什麼好的方案。

覺得最徹底的應該是重寫RadioButtonList 的SelectedValue屬性,當set該屬性時如果在值列表裡未查到值則忽略而不是報錯。另一個權益之計就是仿造DropdownList的解決方案,但要麻煩的多,在DataBinding事件之前添加一個具有空值的item,然後在render之前在去掉該item。

                <asp:RadioButtonList ID="RadioButtonList1" runat="server" SelectedValue='<%# Bind("FiledlNameInDB") %>'  RepeatDirection="Horizontal" RepeatLayout="Flow" OnInit="RadioButtonList1_Init" OnPreRender="RadioButtonList1_PreRender"
                    <asp:ListItem Value="True">YES</asp:ListItem>
                    <asp:ListItem Value="False">NO</asp:ListItem>
                </asp:RadioButtonList>

        protected void RadioButtonList1_Init(object sender, EventArgs e)
        {
            RadioButtonList rbl = sender as RadioButtonList;
            rbl.Items.Add(new ListItem(string.Empty));
        }

 

        protected void RadioButtonList1_PreRender(object sender, EventArgs e)
        {
            RadioButtonList rbl = sender as RadioButtonList;
            rbl.Items.Remove(string.Empty);

        }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.