Hi Corobori,
You need to use Page.Validate function with group name before calling IsValid function.
Check this example. Now please take its reference and correct your code.
HTML
<div>
Country:<asp:DropDownList ID="ddlCountries" runat="server" AppendDataBoundItems="true"
onchange="PopulateStates();">
<asp:ListItem Text="Please select" Value="0"></asp:ListItem>
</asp:DropDownList>
<br />
<br />
State:<asp:DropDownList ID="ddlStates" runat="server"
onchange="PopulateCities();">
<asp:ListItem Text="Please select" Value="0"></asp:ListItem>
</asp:DropDownList>
<br />
<br />
City:<asp:DropDownList ID="ddlCities" runat="server">
<asp:ListItem Text="Please select" Value="0"></asp:ListItem>
</asp:DropDownList>
<asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="ddlCities" ErrorMessage="Missing"
MaximumValue="999999" MinimumValue="1" Type="Integer" ValidationGroup="gr"></asp:RangeValidator>
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="Submit" ValidationGroup="gr" />
</div>
<script type="text/javascript">
var pageUrl = '<%=ResolveUrl("~/CS.aspx")%>'
function PopulateStates() {
$("#<%=ddlStates.ClientID%>").attr("disabled", "disabled");
$("#<%=ddlCities.ClientID%>").attr("disabled", "disabled");
if ($('#<%=ddlCountries.ClientID%>').val() == "0") {
$('#<%=ddlStates.ClientID %>').empty().append('<option selected="selected" value="0">Please select</option>');
$('#<%=ddlCities.ClientID %>').empty().append('<option selected="selected" value="0">Please select</option>');
}
else {
$('#<%=ddlStates.ClientID %>').empty().append('<option selected="selected" value="0">Loading...</option>');
$.ajax({
type: "POST",
url: pageUrl + '/PopulateStates',
data: '{countryId: ' + $('#<%=ddlCountries.ClientID%>').val() + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnCountriesPopulated,
failure: function (response) {
alert(response.d);
}
});
}
}
function PopulateCities() {
$("#<%=ddlCities.ClientID%>").attr("disabled", "disabled");
if ($('#<%=ddlStates.ClientID%>').val() == "0") {
$('#<%=ddlCities.ClientID %>').empty().append('<option selected="selected" value="0">Please select</option>');
}
else {
$('#<%=ddlCities.ClientID %>').empty().append('<option selected="selected" value="0">Loading...</option>');
$.ajax({
type: "POST",
url: pageUrl + '/PopulateCities',
data: '{stateId: ' + $('#<%=ddlStates.ClientID%>').val() + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnCitiesPopulated,
failure: function (response) {
alert(response.d);
}
});
}
}
function OnCountriesPopulated(response) {
PopulateControl(response.d, $("#<%=ddlStates.ClientID %>"));
}
function OnCitiesPopulated(response) {
PopulateControl(response.d, $("#<%=ddlCities.ClientID %>"));
}
function PopulateControl(list, control) {
if (list.length > 0) {
control.removeAttr("disabled");
control.empty().append('<option selected="selected" value="0">Please select</option>');
$.each(list, function () {
control.append($("<option></option>").val(this['Value']).html(this['Text']));
});
}
else {
control.empty().append('<option selected="selected" value="0">Not available<option>');
}
}
</script>
Namespaces
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.PopulateStates();
}
}
private void PopulateStates()
{
string strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
string strQuery = "select CountryId, CountryName from Countries";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
con.Open();
ddlCountries.DataSource = cmd.ExecuteReader();
ddlCountries.DataTextField = "CountryName";
ddlCountries.DataValueField = "CountryId";
ddlCountries.DataBind();
con.Close();
}
[System.Web.Services.WebMethod()]
public static ArrayList PopulateStates(int countryId)
{
ArrayList list = new ArrayList();
string strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
string strQuery = "select StateId, StateName from States where CountryId=@CountryId";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@CountryId", countryId);
cmd.CommandText = strQuery;
cmd.Connection = con;
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
list.Add(new ListItem(sdr["StateName"].ToString(), sdr["StateId"].ToString()));
}
con.Close();
return list;
}
[System.Web.Services.WebMethod()]
public static ArrayList PopulateCities(int stateId)
{
ArrayList list = new ArrayList();
string strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
string strQuery = "select CityId, CityName from Cities where StateId=@StateId";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@StateId", stateId);
cmd.CommandText = strQuery;
cmd.Connection = con;
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
list.Add(new ListItem(sdr["CityName"].ToString(), sdr["CityId"].ToString()));
con.Close();
return list;
}
private void PopulateDropDownList(ArrayList list, DropDownList ddl)
{
ddl.DataSource = list;
ddl.DataTextField = "Text";
ddl.DataValueField = "Value";
ddl.DataBind();
}
protected void Submit(object sender, EventArgs e)
{
string continent = Request.Form[ddlCountries.UniqueID];
string country = Request.Form[ddlStates.UniqueID];
string city = Request.Form[ddlCities.UniqueID];
PopulateDropDownList(PopulateStates(int.Parse(continent)), ddlStates);
PopulateDropDownList(PopulateCities(int.Parse(country)), ddlCities);
ddlStates.Items.FindByValue(country).Selected = true;
ddlCities.Items.FindByValue(city).Selected = true;
this.Validate("gr");
if (this.IsValid)
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Valid');", true);
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Not Valid');", true);
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Me.PopulateStates()
End If
End Sub
Private Sub PopulateStates()
Dim strConnString As String = ConfigurationManager.ConnectionStrings("conString").ConnectionString
Dim strQuery As String = "select CountryId, CountryName from Countries"
Dim con As SqlConnection = New SqlConnection(strConnString)
Dim cmd As SqlCommand = New SqlCommand
cmd.CommandType = CommandType.Text
cmd.CommandText = strQuery
cmd.Connection = con
con.Open()
ddlCountries.DataSource = cmd.ExecuteReader
ddlCountries.DataTextField = "CountryName"
ddlCountries.DataValueField = "CountryId"
ddlCountries.DataBind()
con.Close()
End Sub
<System.Web.Services.WebMethod()>
Public Shared Function PopulateStates(ByVal countryId As Integer) As ArrayList
Dim list As ArrayList = New ArrayList
Dim strConnString As String = ConfigurationManager.ConnectionStrings("conString").ConnectionString
Dim strQuery As String = "select StateId, StateName from States where CountryId=@CountryId"
Dim con As SqlConnection = New SqlConnection(strConnString)
Dim cmd As SqlCommand = New SqlCommand
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("@CountryId", countryId)
cmd.CommandText = strQuery
cmd.Connection = con
con.Open()
Dim sdr As SqlDataReader = cmd.ExecuteReader
While sdr.Read
list.Add(New ListItem(sdr("StateName").ToString, sdr("StateId").ToString))
End While
con.Close()
Return list
End Function
<System.Web.Services.WebMethod()>
Public Shared Function PopulateCities(ByVal stateId As Integer) As ArrayList
Dim list As ArrayList = New ArrayList
Dim strConnString As String = ConfigurationManager.ConnectionStrings("conString").ConnectionString
Dim strQuery As String = "select CityId, CityName from Cities where StateId=@StateId"
Dim con As SqlConnection = New SqlConnection(strConnString)
Dim cmd As SqlCommand = New SqlCommand
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("@StateId", stateId)
cmd.CommandText = strQuery
cmd.Connection = con
con.Open()
Dim sdr As SqlDataReader = cmd.ExecuteReader
While sdr.Read
list.Add(New ListItem(sdr("CityName").ToString, sdr("CityId").ToString))
End While
con.Close()
Return list
End Function
Private Sub PopulateDropDownList(ByVal list As ArrayList, ByVal ddl As DropDownList)
ddl.DataSource = list
ddl.DataTextField = "Text"
ddl.DataValueField = "Value"
ddl.DataBind()
End Sub
Protected Sub Submit(ByVal sender As Object, ByVal e As EventArgs)
Dim continent As String = Request.Form(ddlCountries.UniqueID)
Dim country As String = Request.Form(ddlStates.UniqueID)
Dim city As String = Request.Form(ddlCities.UniqueID)
PopulateDropDownList(PopulateStates(Integer.Parse(continent)), ddlStates)
PopulateDropDownList(PopulateCities(Integer.Parse(country)), ddlCities)
ddlStates.Items.FindByValue(country).Selected = True
ddlCities.Items.FindByValue(city).Selected = True
Me.Validate("gr")
If Me.IsValid Then
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('Valid');", True)
Else
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('Not Valid');", True)
End If
End Sub
Screenshot