我很震惊。希望你理解我的问题 我有一个名为“地址类型”的下拉列表字段,其中包含Home,Office,Other,Hostel等值。我有另一个名为ID的文本字段,它是一个整数类型。我想自动从DB中获取基于文本字段的下拉列表的值。
Example:
ID 1 : Drop Down Values-Home, Other
ID 2 : Drop Down Values-Home, Other, Hostel
ID 3 : Drop Down Values-Office.
SQL查询:
SELECT DISTINCT Address_Type FROM Contact_AddressInfo WHERE ContactID =XXX
ASP代码:
protected void DropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = new DropDownList();
con.Open();// Already declared the connection string
SqlCommand cmd = new SqlCommand("SELECT DISTINCT Address_Type FROM Contact_AddressInfo WHERE ContactID ='" + TextBox.Text + "'",con);
DropDownList.SelectedValue = cmd.ToString();
cmd.ExecuteNonQuery();
con.Close();
ddl.DataSource = dataset.Tables[0].DefaultView;
ddl.DataValueField = "Address_Type";
ddl.DataTextField = "Address_Type";
ddl.DataBind();
}
Query在sql Server中工作正常,但我正在尝试在asp.net中实现。任何帮助都很有帮助
答案 0 :(得分:1)
在文本框中更改值时,是否要更改下拉列值更改?如果是,则在您的代码中生成文本框的OnChange()事件,并通过传递文本框值重新绑定您的下拉列表。
con.Open();
SqlCommand cmd = new SqlCommand("SELECT DISTINCT Address_Type FROM
Contact_AddressInfo WHERE ContactID ='" + TextBox.Text + "'", con);
SqlDataReader ddlValues;
ddlValues = cmd.ExecuteReader();
ddl.DataSource = ddlValues;
ddl.DataValueField = "Address_Type";
ddl.DataTextField = "Address_Type";
ddl.DataBind();
答案 1 :(得分:0)
试试这个..我希望这对你的项目有用..
con.Open();
SqlCommand cmd = new SqlCommand("SSELECT DISTINCT Address_Type FROM Contact_AddressInfo WHERE ContactID ='" + TextBox.Text + "'", con);
SqlDataReader ddlValues;
ddlValues = cmd.ExecuteReader();
ddl.DataSource = ddlValues;
ddl.DataValueField = "Address_Type";
ddl.DataTextField = "Address_Type";
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("--select Item Name--", "0"));
con.Close();
答案 2 :(得分:0)
试试这个......
ddl.DataValueField = "Address_Type";
ddl.DataTextField = "Address_Type";
ddl.DataBind();
获取下拉列表中选择的等效地址。
ddl.SelectedValue = Int32.parse(TextBox.Text);
答案 3 :(得分:0)
删除DropDownList.SelectedValue = cmd.ToString();并使用DataAdapter填充您的DataTable。因为现在你的命令没有向你的代码返回任何值。