简体   繁体   English

将项目插入下拉列表

[英]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) . 我想基于dropdownlist1(来自表1)的所选项目显示dropdownlist2(来自表2)中的项目。

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...? 在下面,我只是尝试基于dropdownlist1中的值从table2中选择lang列值。((仅插入dropdownlist1中))是正确的代码...吗?

    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. 如果只希望使用在刚刚提到的查询后返回的值填充DropDownList2,则只需对它进行数据绑定。

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): 而且,您还可以通过这种方式将值字段添加到下拉列表中(但您必须修改sql查询,以使其返回2列):

"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. 尝试连接dropdownlist 1上的SelectedIndexChanged事件,然后绑定dropdownlist 2上的事件。 I am assuming you are using Asp.net... 我假设您正在使用Asp.net ...

This would be in your aspx page: 这将在您的aspx页面中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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