简体   繁体   中英

Dropdownlist validate against text field using OnServerValidate in ASP.NET

I have Country Dropdownlist with value eg: "US and NON US" and a text field name "State"

when the user enter State of US for eg "MN" in text field and select US from drop down I need to validate the state entered in textfield with the state values of US from the Database table

There is a table which contains only states of "US"

Also when the user select "Non US" from drop down and when the button click I need to validate the state for NON US since there is no state values for "Non US" from the Database table and show Message like "only US is valid" I tried the code as below but dont know how to get the State value in the Function. what code I need add to work on this. I am new to ASP.NET. Thanks in Advance for any help.

 Country:<asp:dropdownlist id="country_add" Runat="server" TabIndex="27">
                                    <asp:ListItem Selected="True">Select</asp:ListItem>
                                    <asp:ListItem Value="US"> US </asp:ListItem>
                                    <asp:ListItem Value="Non US"> Non US</asp:ListItem>
                                    </asp:dropdownlist> 
                                <asp:customvalidator id="country_Batch" runat="server" ControlToValidate="txtMatState" OnServerValidate="validate_State"
                                        ErrorMessage="*" text="*"></asp:customvalidator>


    <asp:textbox id="txtMatState" runat="server" TabIndex="21"></asp:textbox></li>

Validation:

       Sub validate_State(ByVal s As Object, ByVal e 
          As ServerValidateEventArgs)
  Dim objConn As New SqlConnection(sConn)           
            Dim cmdState As SqlCommand
            Dim dtrState As SqlDataReader              
            objConn.Open()
            e.IsValid = False
    Dim sSQL As String = "SELECT * FROM country WHERE 
[STATE] = '" & e.Value & "' "
cmdState = New SqlCommand(sSQL, objConn)
            dtrState = cmdState.ExecuteReader()
            While dtrState.Read()
                e.IsValid = True
            End While

            objConn.Close()
        End Sub

The validation takes place in your page code behind - so just access the controls you want, eg country_add.SelectedValue to get the currently selected value from the dropdownlist.

To add a custom error message in the validation-handler, just set the property of the CustomValidator like this:

country_Batch.ErrorMessage = "your desired error message"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM