對於輸入值二選一這種情況(比如是、否,男、女),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);
}