我想要做的是在 dropdown2 上不显示当前在 dropdown1 中选择的内容。
您的问题是,在页面加载上,所有内容都“重置”了。所以 DropDownList1.SelectedItem 是列表中的第一个或默认项。如果 DropDownList1.SelectedItem 为“One”,则它将始终从 DropDownList2 中删除“One”。
您需要的是 DropDownList1 的按钮或 OnSelectedIndexChanged 事件。
试试我在下面所做的,它对我有用。
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="ddlOne" runat="server" OnSelectedIndexChanged="ddlOne_OnSelectedIndexChanged" AutoPostBack="true" />
<br />
<br />
<asp:DropDownList ID="ddlTwo" runat="server" />
<br />
<br />
<asp:Button ID="btRemove" runat="server" Text="Remove"
onclick="btRemove_Click" />
</div>
</form>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Bind data
BindLists();
}
}
/// <summary>
/// Removes whatever Selected Item from ddlTwo that is
/// currently selected in ddlOne.
/// </summary>
private void RemoveFromTwoWhatIsSelectedInOne()
{
ddlTwo.Items.Remove(ddlOne.SelectedItem);
}
/// <summary>
/// Click handler for btRemove. Calls the method
/// RemoveFromTwoWhatIsSelectedInOne()
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btRemove_Click(object sender, EventArgs e)
{
RemoveFromTwoWhatIsSelectedInOne();
}
/// <summary>
/// OnSelectedIndexChanged handler for ddlOne. Calls the method
/// RemoveFromTwoWhatIsSelectedInOne()
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void ddlOne_OnSelectedIndexChanged(object sender, EventArgs e)
{
RemoveFromTwoWhatIsSelectedInOne();
}
/// <summary>
/// Binds a list of names the two Drop Down Lists, ddlOne and ddlTwo, by using
/// the same Data Source from the Manager.
/// </summary>
private void BindLists()
{
// Get the data
Manager theManager = new Manager();
List<Names> theNames = theManager.GetNames();
// Assign the data source
ddlOne.DataSource = theNames;
ddlTwo.DataSource = theNames;
// Bind each drop down list
ddlOne.DataBind();
ddlTwo.DataBind();
}