if (lb.Items.Count < 1)
{
      Page.RegisterStartupScript("","<script>alert('aa');</script>");
      return;
}

解决方案 »

  1.   

    RequiredFieldValidator验证控件本身就能够达到你的要求
    RequiredFieldValidator1.ControlToValiddate = ListBox1;
      

  2.   

    各位大虾,能不能讲详细点?customValidator有一个客户端验证函数属性和一个服务端验证事件,我应该把验证代码放在哪个地方呢?两个地方我都试过了,但是在客户端的语言是js,不能“ListBox1.Items.Count>0”这样用吧?可是在服务端验证,就说页面先要被提交,这个流程我搞不清了,我希望的是可以像对文本框的验证那样,在还没提交前就能验出来,并显示自定义的出错提示,怎么办呢?
    另外,RequiredFieldValidator1.ControlToValiddate = ListBox1 不行,我试过了
      

  3.   

    you can just use a RequiredFieldValidator, for example
    <asp:ListBox id="ListBox1" runat="server" SelectionMode="Multiple">
        <asp:ListItem Value="">Please Select At Least One</asp:ListItem>
                                <asp:ListItem Value=".89">apples</asp:ListItem>
                                <asp:ListItem Value=".49">bananas</asp:ListItem>
                                <asp:ListItem Value="2.99">cherries</asp:ListItem>
                                <asp:ListItem Value="1.49">grapes</asp:ListItem>
                                <asp:ListItem Value="2.00">mangos</asp:ListItem>
                                <asp:ListItem Value="1.09">oranges</asp:ListItem>
                            </asp:ListBox>
        
          &nbsp;&nbsp;     <asp:RequiredFieldValidator id="RequiredFieldValidator1" 
               InitialValue="" 
               ControlToValidate="ListBox1"
               ErrorMessage="Required field!"
               runat="server"/>
      

  4.   

    楼上,我的意思是,这个dropdownlist的listitem都是动态添加的,我要验证的是在提交时这里面至少已添加了一个listitem
      

  5.   

    >>>要验证的是在提交时这里面至少已添加了一个listitemyou only need to remember the old count of options for the SELECT and check the new count of options to see if the latter is larger>>dropdownlist的listitem都是动态添加的?if you mean they are added by javascript, then I can warn you, it will probably not work, since DropDownList uses ViewState to restore its ListItemCollection, consider to add the new item(s) to a hidden variable...
      

  6.   

    思归兄,我这个listbox是很麻烦的,它与别一个listbox交互,两者的选项可以移来移去,所以才有了要限制第一个listbox在提交时至少要有一个选项的限制,
    第二点,选项的添删不是用js完成的,而是回送到服务端完成的,应该不存在你说的第二个问题吧,我只是想验证在第一个listbox里到底有没有选项,同时想让验证出错时显示一条红色的自定义消息(与普通文本框验证一样),有没有好的办法解决啊
      

  7.   

    like I said, if you only need to 验证在第一个listbox里到底有没有选项, you could just use a RequireFieldValidator, if you insist on using CustomValidator, as you might know, CustomValidator is not triggered if the value of the validating ListBox is empty (that means you still need a RequireFieldValidator)of course, you can always write an onsubmit event handler for your form and validate anything you want