在没有数据库连接的情况下,根据第一个下拉列表中的项目选择填充两个下拉列表
本文关键字:下拉列表 填充 项目 选择 两个 第一个 数据库连接 情况下 | 更新日期: 2023-09-27 18:13:57
我有三个下拉列表ddl1, ddl2和ddl3。
现在在ddl1中选择一个项时,应该填充ddl2和ddl3中相应的项。
例如:-如果我在ddl1中选择"India",那么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();
}
如果要从数据库中获取国家数据,则应同时获取所有州和城市数据。
那么您应该使用dataview过滤数据。因此,只需调用一次数据库就可以满足您的需求。
可能对你有帮助。
如果您想避免访问数据库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下拉列表。同样的方法也适用于城市下拉菜单
几天前我也遇到过同样的情况,应该在页面加载时填充列表中的所有数据,然后通过jquery和ajax过滤列表,并动态地将它们绑定到下拉列表。我试过了,但没有成功。所以我使用了Ajaxtoolkit的级联下拉菜单
因为您没有链接到数据库,您最好使用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");
}
在每个国家复制并通过这个,这是非常重复的,但很有效。