【问题标题】:inserting items to dropdownlist将项目插入下拉列表
【发布时间】:2009-09-08 07:38:08
【问题描述】:

我想根据下拉列表1(来自表1)的选定项目显示我的下拉列表2(来自表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);

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

【问题讨论】:

    标签: c# asp.net data-binding


    【解决方案1】:

    要将新值添加到现有下拉列表中,您应该手动添加新行:

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

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

    【讨论】:

      【解决方案2】:

      如果您只希望 DropDownList2 填充您刚才提到的查询后返回的值,您应该只是 Databind 它。

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

      祝你好运! ;)

      【讨论】:

        【解决方案3】:

        尝试在下拉列表一上连接 SelectedIndexChanged 事件,然后绑定下拉列表二。我假设您使用的是 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();
         }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-09-11
          • 1970-01-01
          • 2010-11-09
          • 2015-06-24
          • 1970-01-01
          • 2017-12-02
          • 1970-01-01
          相关资源
          最近更新 更多