Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将项目插入dropdownlist_C#_Asp.net_Data Binding - Fatal编程技术网

C# 将项目插入dropdownlist

C# 将项目插入dropdownlist,c#,asp.net,data-binding,C#,Asp.net,Data Binding,我想根据dropdownlist1(来自表1)的所选项目显示我的dropdownlist2(来自表2)中的项目 在下面,我只是尝试根据dropdownlist1中的值从表2中选择lang列值((只是插入dropdownlist1)) 那是正确的代码吗 SqlDataAdapter da = new SqlDataAdapter( "Select lang from table2 whereheatre=@d",connect.con()); da.SelectCom

我想根据dropdownlist1(来自表1)的所选项目显示我的dropdownlist2(来自表2)中的项目

在下面,我只是尝试根据dropdownlist1中的值从表2中选择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);

是否有其他方法可以这样做…?

要将新值添加到现有的dropdownlist中,您应该手动添加新行:

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

或者,在将它们绑定到dropdownlist之前,您应该先将它们绑定到dropdownlist。

如果您只想用刚才提到的查询后返回的值填充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列):


祝你好运

尝试在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"  />
<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();
 }