在页面加载时从.aspx中删除下拉项

时间:2012-05-03 16:48:13

标签: c# asp.net

我有以下代码,当选择dropdown1中的值时,从dropdown2中删除dropdown1中选择的项目:

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList2.Items.Remove(DropDownList1.SelectedItem);

    }

工作正常。但是我尝试在pageload中添加相同的代码,但它并没有删除我猜的值,因为没有选择任何内容我该如何实现?

 protected void Page_Load(object sender, EventArgs e)
    {

        DropDownList2.Items.Remove(DropDownList1.SelectedItem);
    }

这是什么不起作用,有什么想法?

2 个答案:

答案 0 :(得分:0)

你有没有尝试过?

if(!IsPostback)
{
    DropDownList2.Items.Remove(DropDownList1.SelectedItem);
}

Page_Load活动中?另外,你如何绑定数据?为什么不在适当的Selected_IndexChanged而不是DropdowsList的{​​{1}}上执行此操作?在我看来,这就是这段代码所属的地方。

答案 1 :(得分:0)

  

我想要做的是在dropdown2上没有显示当前在dropdown1中选择的内容。

你的问题是什么,在Page Load上,所有东西都“重置”了。所以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();
    }