如何在asp.net中验证列表框

如何在asp.net中验证列表框,asp.net,listbox,Asp.net,Listbox,我有一个列表框,如果用户单击“提交”按钮而没有从列表框中选择任何值,我想验证它。 现在我正在执行以下操作,但我无法看到验证消息。我哪里出错了 aspx: 在代码隐藏中,使用以下代码 protected override void Page_Load(object sender, EventArgs e) { this.ddList.SelectedIndex = -1; } 并在提交按钮上检查ddList.SelectedIndex是否为-1。如果仍然为-1,则显示错误。Html

我有一个列表框,如果用户单击“提交”按钮而没有从列表框中选择任何值,我想验证它。
现在我正在执行以下操作,但我无法看到验证消息。我哪里出错了

aspx:


在代码隐藏中,使用以下代码

protected override void Page_Load(object sender, EventArgs e)
{
    this.ddList.SelectedIndex = -1;
}
并在提交按钮上检查ddList.SelectedIndex是否为-1。如果仍然为-1,则显示错误。

Html

    <form id="form1" runat="server"> 
    <asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple">
   <asp:ListItem Value="1">--Select--</asp:ListItem>
   <asp:ListItem  Value="2" ></asp:ListItem>
    <asp:ListItem  Value="3" ></asp:ListItem>
   <asp:ListItem  Value="4" ></asp:ListItem>
    </asp:ListBox>

        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="select listitems" 
            ControlToValidate="ListBox1" InitialValue="" EnableTheming="True" ForeColor="#FF3300" ViewStateMode="Enabled">

        </asp:RequiredFieldValidator>

         <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
    </form>


尝试提供默认值
并检查所选值是否仍然为该值。@Hassaniam列表框正在从cs页面动态加载,我无法硬编码该值。您得到的错误是什么?“提交”按钮中selectedIndex的初始值是多少?我没有收到错误,但我也看不到验证消息。请尝试将此验证
执行此操作,但我仍然看不到任何验证消息尝试将
ErrorMessage=“Required”
添加为必填字段验证程序的属性。
protected override void Page_Load(object sender, EventArgs e)
{
    this.ddList.SelectedIndex = -1;
}
    <form id="form1" runat="server"> 
    <asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple">
   <asp:ListItem Value="1">--Select--</asp:ListItem>
   <asp:ListItem  Value="2" ></asp:ListItem>
    <asp:ListItem  Value="3" ></asp:ListItem>
   <asp:ListItem  Value="4" ></asp:ListItem>
    </asp:ListBox>

        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="select listitems" 
            ControlToValidate="ListBox1" InitialValue="" EnableTheming="True" ForeColor="#FF3300" ViewStateMode="Enabled">

        </asp:RequiredFieldValidator>

         <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
    </form>
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>