asp.net Validation on DropDownList box

2019-04-16 16:52发布

问题:

I have a dropdownlist (cboViewAlbums) which has displays album values. The first item is a Please select an album.... I am trying to use validation which when lb_create_album linkButton is clicked throws an error if the cboViewAlbums list has the value 0 selected. Below is the code for the this and my attempt:

<asp:DropDownList ID="cboViewAlbums" runat="server" 
         DataSourceID="SqlDataSource1" DataTextField="album_name" 
         DataValueField="album_id" Width="250px" AutoPostBack="True" AppendDataBoundItems="true">
         <asp:ListItem Value="0">Please select an album...</asp:ListItem>
         </asp:DropDownList>
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
     <asp:LinkButton ID="lb_create_album" runat="server">Create Album</asp:LinkButton>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:fpaConnectionString %>"
        SelectCommand="SELECT [album_id], [album_name] FROM [fpa_albums] ORDER BY [album_name]">
    </asp:SqlDataSource>
     <br />
     <asp:HyperLink CssClass="example7" ID="hLinkUploadPhotos" NavigateUrl="multiple_upload.aspx" runat="server">Upload Multiple Photos</asp:HyperLink>
     <br />
     <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
         ControlToValidate="cboViewAlbums" ErrorMessage="Please Select an Album" 
         InitialValue="Please select an album..."></asp:RequiredFieldValidator>

Any idea how I can get this working?

Thanks

回答1:

You have to use Range validator with dropdown list & set mininmum value greater then 0 & maximum value to set any max value , aslo provide type value of min & max and that is integer.

Below is the sample code i have make for you you have to bind your datasource insted of static list items.

<asp:DropDownList runat="server" ID="ddl1" >
        <asp:ListItem Value="0" Text="Select value" />
        <asp:ListItem Value="1" Text="text1" />
        <asp:ListItem Value="2" Text="text2" />
    </asp:DropDownList>
    <asp:RangeValidator ErrorMessage="Please select value" ControlToValidate="ddl1" runat="server"
        MinimumValue="1" MaximumValue="100000000" Type=Integer />
    <asp:Button Text="text" runat="server"  />

If this helpful to you please mark as an answer

Thanks

Arun



回答2:

First, you can't do validation with HyperLink, better use the LinkButton. HyperLink does not do post back, so that's your first error. Second, on your RequiredFieldValidator, put the initialvalue=0, and that should fix your problem.

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
     ControlToValidate="cboViewAlbums" ErrorMessage="Please Select an Album" 
     InitialValue="0"></asp:RequiredFieldValidator>