简体   繁体   中英

inserting items to dropdownlist

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...?

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.

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! ;)

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();
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM