簡體   English   中英

如何動態填充dropdownlist循環

[英]How to populate dropdownlist dynamically loop

我有一個下拉列表,有6種可能的選擇。

<asp:DropDownList runat="server" ID="ddlSel1" 
        onselectedindexchanged="ddlSel1_SelectedIndexChanged" AutoPostBack="true">
        <asp:ListItem></asp:ListItem>
<asp:ListItem>One</asp:ListItem>
<asp:ListItem>Two</asp:ListItem>
<asp:ListItem>Three</asp:ListItem>
<asp:ListItem>Four</asp:ListItem>
<asp:ListItem>Five</asp:ListItem>
<asp:ListItem>Six</asp:ListItem>

</asp:DropDownList>

一旦用戶從ddlSel1中選擇了一個選項,我希望ddlSel2填充相同的列表,不包括在ddlSel1中選擇的列表。

我是這樣做的:

if (ddlSel1.SelectedItem.Value == "One")
    {
        string[] stringArray = { "", "TWO", "THREE", "FOUR", "FIVE", "SIX" };
        ddlSel2.DataSource = stringArray;
        ddlSel2.DataBind();
    }

我的問題是如何在不必每次都輸入單獨的IF語句的情況下循環使用它。

您可以從ddlSel1.DataSource獲取原始源數組,然后使用Enumerable.Except與新string[]的所選項目一樣:

string[] originalSource = ddlSel1.DataSource as string[];
if(originalSource != null && ddlSel1.SelectedItem != null)
{
  ddlSel2.DataSource = originalSource.Except(new [] { ddlSel1.SelectedItem.Value.ToString() });
  ddlSel2.DataBind();
}

最好是檢查originalSourceSelectedItem是否為null。

這是使用Linq的替代方案:

首先,您在其他地方定義可能的值:

string[] values { "ONE", "TWO", ..., "SIX" };

然后在你的功能塊里面:

ddlSel2.DataSource = (from v in values where !v.Equals(ddlSel1.SelectedItem.Value) select v).ToList();
ddlSel2.DataBind();

別忘了輸入:

using System;
using System.Linq;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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