簡體   English   中英

將項目插入下拉列表

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM