我在 SQL Server 中有2个表,
country_Id country 1 India 2 Australia 3 Netherlands
第二个表是状态
state_Id country_Id state 1 2 abc 2 2 xyz 3 3 pqr 4 1 lmn 5 1 rst
在页面加载国家/地区自动进入dropdown1
,当我在第一个下拉列表中选择澳大利亚时,在第二个下拉列表abc
和xyz
将会是所示。
我做了,但我收到错误查询错误。
什么是正确的查询?
我的代码是:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
adap = new SqlDataAdapter("SELECT state FROM table_state ,table_country where country = '"
+ DropDownList1.SelectedItem.ToString()
+ "' on table_state.country_Id = table_country.country_Id", con);
con.Open();
ds1 = new DataSet();
adap.Fill(ds1);
DropDownList2.DataSource = ds1;
DropDownList2.DataValueField = "state";
DropDownList2.DataTextField = "state"
DropDownList2.DataBind();
con.Close();
}
答案 0 :(得分:1)
在代码DropDownList1_SelectedIndexChanged
方法
adap = new SqlDataAdapter("SELECT state FROM table_state where country_Id = '"
+ DropDownList1.SelectedValue + "'", con);
答案 1 :(得分:0)
你在论证中的查询应该是(从我收集的内容):
"SELECT distinct a.state FROM table_state a inner join table_country b on
a.country_Id = b.country_Id
where a.country = '" + DropDownList1.SelectedItem.ToString() + "'"
答案 2 :(得分:0)
添加DropDownList1.DataValueField = "country_Id"
并使用以下内容,无需加入。
这很简单
adap = new SqlDataAdapter(String.Format("SELECT state FROM table_state where country_Id = '{0}'",DropDownList1.SelectedValue), con);
答案 3 :(得分:0)
使用下拉值直接查询不是一个好习惯,你可以在SqlDataAdapter中使用参数:
adap = new SqlDataAdapter("SELECT distinct a.state
FROM table_state a
inner join table_country b
on a.country_Id = b.country_Id
where a.country = @Country");
adap.SelectCommand.Parameters.AddWithValue("@Country",DropDownList1.SelectedValue);