2009-09-08 38 views
0

我想基于dropdownlist1(从表1)中选择的项目,在我的dropdownlist2(来自表2)中显示项目。将项目插入到下拉列表中

在以下内容中,我只是尝试从table2中选择lang列值,该值基于dropdownlist1中的值。((仅仅插入dropdownlist1)) 是那个正确的代码...?

SqlDataAdapter da = new SqlDataAdapter(
     "Select lang from table2 [email protected]",connect.con()); 
    da.SelectCommand.Parameters.AddWithValue("@d", DropDownList1.SelectedItem.Text); 
    DataSet ds=new DataSet(); 
    da.Fill(ds,"l1"); 
    DropDownList2.Items.Add(ds); 

有没有其他方法可以做到这一点......?

回答

2

要添加新值到现有的下拉列表,你应该manualy添加新行:

foreach (DataRow dr in ds.Tables[0].Rows) 
{ 
    DropDownList2.Items.Add(new ListItem(dr["TextField"].ToString(), dr["ValueField"].ToString())); 
} 

或者,你应该merge datatables它们绑定到您的下拉列表之前。

0

如果您只希望使用刚刚提到的查询之后返回的值填充DropDownList2,那么您应该只是对它进行数据绑定。

SqlDataAdapter da = new SqlDataAdapter(
    "Select lang from table2 [email protected]",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 [email protected]" 

DropDownList2.DataSource = ds; 
DropDownList2.DataTextField = "lang"; 
DropDownList2.DataValueField= "colId "; 
DataBind(); 

祝你好运! ;)

0

尝试连接dropdownlist上的SelectedIndexChanged事件,然后绑定dropdownlist两个。我假设你正在使用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(); 
} 
相关问题