我有三个下拉列表 ddl1、ddl2 和 ddl3。
现在,在选择 ddl1 的项目时,应填充 ddl2 和类似的 ddl3 中的相应项目。
例如:- 如果我在 ddl1 中选择“印度”,那么 ddl2 应该显示所有州,而 ddl3 应该显示印度国家的所有城市。我希望在没有任何数据库连接的情况下执行此操作(只是来自 html 的静态)。请帮忙!!!。谢谢。
我有三个下拉列表 ddl1、ddl2 和 ddl3。
现在,在选择 ddl1 的项目时,应填充 ddl2 和类似的 ddl3 中的相应项目。
例如:- 如果我在 ddl1 中选择“印度”,那么 ddl2 应该显示所有州,而 ddl3 应该显示印度国家的所有城市。我希望在没有任何数据库连接的情况下执行此操作(只是来自 html 的静态)。请帮忙!!!。谢谢。
private SqlConnection conn = your connection string;
public void Bind_ddlcountry()
{
conn.Open();
SqlCommand cmd = new SqlCommand("select countryid,country from tblcountry", conn);
SqlDataReader dr = cmd.ExecuteReader();
ddlcountry.DataSource = dr;
ddlcountry.Items.Clear();
ddlcountry.Items.Add("--Please Select country--");
ddlcountry.DataTextField = "Country";
ddlcountry.DataValueField = "CountryId";
ddlcountry.DataBind();
conn.Close();
}
// 类似地绑定你的州和城市..
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{ Bind_ddlcountry(); }
}
protected void ddlcountry_selectedindexchanged(object sender, EventArgs e)
{
Bind_ddlstate();
ddlstate.Focus();
}
protected void ddlstate_selectedindexchanged(object sender, EventArgs e)
{
Bind_ddlcity();
ddlcity.Focus();
}
由于您没有链接到数据库,因此最好使用 IfElse 语句。类似的东西
if (dropdownlist1.selectedValue == "India")
{
dropdownlist2.items.clear();
dropdownlist2.items.add("CityName");
dropdownlist2.items.add("CityName");
dropdownlist2.items.add("CityName");
dropdownlist2.items.add("CityName");
dropdownlist2.items.add("CityName");
dropdownlist2.items.add("CityName");
dropdownlist2.items.add("CityName");
}
为每个国家复制并过去,它非常重复但有效。
如果你想避免命中数据库 3 次,你可以这样做,
Dataset ds= //从SP获取
将国家数据分配给 Datatable 并绑定到国家下拉列表
DataTable country=ds.Tables[0];
DataTable state=ds.Tables[1];
DataTable city=ds.Tables[2];
if (countryTab != null)
{
ddlCountries.DataSource = countryTab;
ddlCountries.DataTextField = "country_name";
ddlCountries.DataValueField = "country_code";
ddlCountries.DataBind();
}
在国家下拉列表的 SelectedIndexChanged 事件上写入查询以过滤状态信息并绑定到状态下拉列表
DataRow[] r = table[1].Select("County like '%" + <selected country value> + "%'");
并将过滤后的结果集绑定到 State 下拉列表。同样的方法也适用于城市下拉菜单。
如果您从数据库中获取国家/地区数据,您应该连同它一起获取所有州和城市数据。
然后你应该用数据视图过滤数据。所以只有 1 个数据库调用可以满足您的需求。
它可能会帮助你。
几天前我遇到了同样的情况,它应该完成一些事情,比如在页面加载时填充列表中的所有数据,然后通过 jquery 和 ajax 过滤列表并将它们动态绑定到下拉列表。我试过但没有成功。所以我使用了 Ajaxtoolkit 的级联下拉菜单。