Reputation: 259
I want to display the items in my dropdownlist2 (from table 2 )based on the selected item of the dropdownlist1(from table 1) .
in the following, i just tried to select the lang column values from table2 based on the value which is in the dropdownlist1..((just to insert into the dropdownlist1)) is that correct code...?
SqlDataAdapter da = new SqlDataAdapter(
"Select lang from table2 whereheatre=@d",connect.con());
da.SelectCommand.Parameters.AddWithValue("@d", DropDownList1.SelectedItem.Text);
DataSet ds=new DataSet();
da.Fill(ds,"l1");
DropDownList2.Items.Add(ds);
is there any other way to do that...?
Upvotes: 0
Views: 2644
Reputation: 2275
Try wiring up the SelectedIndexChanged event on dropdownlist one and then bind dropdownlist two. I am assuming you are using Asp.net...
This would be in your aspx page:
<asp:DropDownList ID="ddlOne"runat="server" OnSelectedIndexChanged="ddlOne_OnSelectedIndexChanged"
AutoPostBack="true" />
<asp:DropDownList ID="ddlTwo"runat="server" DataTextField="lang" DataValueField="colId" />
This would be in your codebehind:
protected void ddlOne_OnSelectedIndexChanged(object sender, EventArgs e)
{
// Go get your data here then bind to it..
ddlTwo.DataSource = "Whatever datasource you want here";
ddlTwo.DataBind();
}
Upvotes: 0
Reputation: 411
If you only want DropDownList2 to be populated with the values that are returned after the query you just mentioned you should just Databind it.
SqlDataAdapter da = new SqlDataAdapter(
"Select lang from table2 whereheatre=@d",connect.con());
da.SelectCommand.Parameters.AddWithValue("@d", DropDownList1.SelectedItem.Text);
DataSet ds=new DataSet();
DropDownList2.DataSource = ds;
DropDownList2.DataTextField = "lang";
DataBind();
Whats more, you can also add a value field to the dropdown list this way(but you must modify the sql query so it wold return 2 columns):
"Select lang,colId from table2 whereheatre=@d"
DropDownList2.DataSource = ds;
DropDownList2.DataTextField = "lang";
DropDownList2.DataValueField= "colId ";
DataBind();
Good luck! ;)
Upvotes: 0
Reputation: 48088
To add the new values into an existing dropdownlist, you should add the new rows manualy :
foreach (DataRow dr in ds.Tables[0].Rows)
{
DropDownList2.Items.Add(new ListItem(dr["TextField"].ToString(), dr["ValueField"].ToString()));
}
Or, you should merge datatables before binding them to your dropdownlist.
Upvotes: 2