从DropDownList中删除所选项目始终会删除顶部的项目

时间:2018-04-06 02:26:57

标签: c# asp.net

我有两个asp.net页面,summary.aspx将使用Response.Redirect("summary.aspx")从第一个asp.net页面调用。

Ticket是一个自定义类,包含4个属性(String name, int age, int seat, int price),它们的getter和setter以及ToString方法。

Session["tickets"]存储Ticket类的对象

我的问题是我有一个名为drop_remove的下拉列表和一个名为btn_remove的按钮。当我单击该按钮时,它应该删除所选项目并从List<Ticket> tickets中删除相应的对象。但是,它始终从下拉列表中删除顶部项目。我是asp.net的新手,请帮忙。

public partial class summary : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        List<Ticket> tickets = (List<Ticket>)Session["tickets"];

        if (Session["eventName"].ToString() != null)
        {
            label_event.Text = Session["eventName"].ToString();
        }

        if (tickets != null)
        {
            displayTickets(tickets);
        }


        if (Session["tickets"] == null)
        {
            tickets = new List<Ticket>();
        }
        else
        {
            tickets = (List<Ticket>)Session["tickets"];
            drop_remove.Items.Clear();
            foreach (Ticket a in tickets)
            {
                drop_remove.Items.Add(a.name.ToString());
            }
        }    
    }

    protected void moreTicekts_Click(object sender, EventArgs e)
    {
        Response.Redirect("default.aspx");
    }


    private void displayTickets(List<Ticket> tickets)
    {
        TextBox1.Text = ""; 
        System.Text.StringBuilder builder = new System.Text.StringBuilder();

        builder.Append(Environment.NewLine);
        foreach (Ticket a in tickets)
        {
            builder.Append(a.ToString() + Environment.NewLine);
        }
        TextBox1.Text += builder.ToString();
    }

    protected void btn_remove_Click(object sender, EventArgs e)
    {
        List<Ticket> tickets = (List<Ticket>)Session["tickets"];


        for (int i = 0; i < tickets.Count; i++)
        {
            if (tickets[i].name.Equals(drop_remove.SelectedItem.ToString()))
            {
                drop_remove.Items.Remove(drop_remove.SelectedItem);
                tickets.RemoveAt(i);
                break;
            }
        }

        Session["tickets"] = null;
        Session["tickets"] = tickets;
    }
}

1 个答案:

答案 0 :(得分:1)

问题在于,每次回发都会在Page_Load中清除drop_remove。结果,从列表中删除了所选项目,因为每个项目都会重新创建。然后,默认情况下,顶部项目成为选定项目。

正如Wael Abbas所说,你需要将这些代码放在if (!IsPostBack)

public partial class summary : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
       if (!IsPostBack) 
       {
            List<Ticket> tickets = (List<Ticket>)Session["tickets"];

            // the rest of the code here
       }
   }
   ...
}