2011-09-01 50 views

回答

6

您必須檢查SelectedIndex。如果它等於-1,則表示沒有選擇。

CheckBoxList list = new CheckBoxList(); 
if (list.SelectedIndex == -1) 
{ 
     //Nothing is selected 
} 
0

這可能是驗證CheckBoxList的最簡單的方法:

使用自定義的驗證:

<asp:CustomValidator runat="server" ID="cvmodulelist" ClientValidationFunction="ValidateModuleList" ErrorMessage="Please Select Atleast one Module"></asp:CustomValidator> 

創建一個JavaScript函數來驗證的CheckBoxList:

// javascript to add to your aspx page 
function ValidateModuleList(source, args) 
{ 
    var chkListModules= document.getElementById ('<%= chkModuleList.ClientID %>'); 
    var chkListinputs = chkListModules.getElementsByTagName("input"); 
    for (var i=0;i<chkListinputs .length;i++) 
    { 
    if (chkListinputs [i].checked) 
    { 
     args.IsValid = true; 
     return; 
    } 
    } 
    args.IsValid = false; 
} 

另一種選擇是創建一個自定義驗證控件,如下所示:

using System; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.ComponentModel; 

namespace CustomValidators 
{ 
    public class RequiredFieldValidatorForCheckBoxLists : System.Web.UI.WebControls.BaseValidator 
    { 
    private ListControl _listctrl; 

    public RequiredFieldValidatorForCheckBoxLists() 
    { 
     base.EnableClientScript = false; 
    } 

    protected override bool ControlPropertiesValid() 
    { 
     Control ctrl = FindControl(ControlToValidate); 

     if (ctrl != null) 
     { 
     _listctrl = (ListControl) ctrl; 
     return (_listctrl != null); 
     } 
     else 
     return false; // raise exception 
    } 

    protected override bool EvaluateIsValid() 
    {  
     return _listctrl.SelectedIndex != -1; 
    } 
    } 
} 
1

CheckBoxList具有屬性的SelectedIndex的SelectedValue

您可以檢查是否有SelectedIndex;如果沒有項目被選中,它將是-1。

相關問題