[英]inserting items to dropdownlist
我想基于dropdownlist1(来自表1)的所选项目显示dropdownlist2(来自表2)中的项目。
在下面,我只是尝试基于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);
还有其他方法可以做到吗...?
要将新值添加到现有的下拉列表中,应手动添加新行:
foreach (DataRow dr in ds.Tables[0].Rows)
{
DropDownList2.Items.Add(new ListItem(dr["TextField"].ToString(), dr["ValueField"].ToString()));
}
或者,您应该合并数据表,然后再将其绑定到下拉列表。
如果只希望使用在刚刚提到的查询后返回的值填充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();
而且,您还可以通过这种方式将值字段添加到下拉列表中(但您必须修改sql查询,以使其返回2列):
"Select lang,colId from table2 whereheatre=@d"
DropDownList2.DataSource = ds;
DropDownList2.DataTextField = "lang";
DropDownList2.DataValueField= "colId ";
DataBind();
祝好运! ;)
尝试连接dropdownlist 1上的SelectedIndexChanged事件,然后绑定dropdownlist 2上的事件。 我假设您正在使用Asp.net ...
这将在您的aspx页面中:
<asp:DropDownList ID="ddlOne"runat="server" OnSelectedIndexChanged="ddlOne_OnSelectedIndexChanged"
AutoPostBack="true" />
<asp:DropDownList ID="ddlTwo"runat="server" DataTextField="lang" DataValueField="colId" />
这将在您的代码背后:
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.