PDA

View Full Version : dropdownlist برای استان ها و شهرستان ها



MAli.webdesign
جمعه 01 مرداد 1395, 10:54 صبح
سلام به دوستان عزیز
ممنون میشم یکی بهم کمک کنه و بهم بگه که چطوری میتونم با استفاده از دوتا dropdownlist استان و شهرستان رو معلوم کنم.
با تشکر.

amir_T_2008
جمعه 01 مرداد 1395, 16:30 عصر
<asp:DropDownList ID="State" class="form-control selectpicker" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="ddlContinents_SelectedIndexChanged">
<asp:ListItem Text="--Select Country--" Value=""></asp:ListItem>
</asp:DropDownList>


<asp:DropDownList ID="city" class="form-control selectpicker" runat="server">
<asp:ListItem Text="--Select city--" Value=""></asp:ListItem>
</asp:DropDownList>






protected void Page_Load(object sender, EventArgs e)
{

if (!IsPostBack)
{
State.AppendDataBoundItems = true;
String strConnString = ConfigurationManager
.ConnectionStrings["ConnectionStr"].ConnectionString;
String strQuery = "select ID, Name from State";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();

cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
State.DataSource = cmd.ExecuteReader();
State.DataTextField = "name";
State.DataValueField = "id";

State.DataBind();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}

protected void ddlContinents_SelectedIndexChanged(object sender, EventArgs e)
{
city.Items.Clear();
city.Items.Add(new ListItem("--Select city--", ""));



city.AppendDataBoundItems = true;
String strConnString = ConfigurationManager
.ConnectionStrings["ConnectionStr"].ConnectionString;
String strQuery = "select ID, Name, StateId from City " +
"where StateId=@StateId";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("@StateId",
State.SelectedItem.Value);
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
city.DataSource = cmd.ExecuteReader();
city.DataTextField = "Name";
city.DataValueField = "name";
city.DataBind();
if (city.Items.Count > 1)
{
city.Enabled = true;
}
else
{
city.Enabled = false;

}
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}