Aseel Nasser
Aseel Nasser

Reputation: 3

List item doesn't removed

I have 2 buttons and a ListBox. When I click the 1st button it is supposed to remove the selected item from ListBox but it doesn't - the ListBox stays the same. What is wrong with the code?

static List<string> Blist = new List<string>();
public int x;
protected void Page_Load(object sender, EventArgs e)
{
    Blist = (List<string>)Session["items"];

    if (Blist != null)
    {
        ListBox1.Items.Clear();
        for (int i = 0; i < Blist.Count; i++)
            ListBox1.Items.Add(Blist[i]);
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    x= ListBox1.SelectedIndex;

    if (x >= 0)
    {
        ListBox1.Items.RemoveAt(x);
        string m = Blist[x];
        Blist.Remove(m);

        Session["items"] = null;
        Session["items"] = Blist;
    }
}

protected void Button2_Click(object sender, EventArgs e)
{
    Session["items"] = null;
}

Upvotes: 0

Views: 151

Answers (1)

Steve&#39;s a D
Steve&#39;s a D

Reputation: 3821

When your page posts back (When the button is clicked) the Page_Load handler fires again. When it does this it repopulates your list. To prevent this you need to check if its a page post back, or the initial load. You do this by checking if Page.IsPostBack is true or false. If its true it means that the page is being posted back (by a button click or whatever). If its not true it means its the initial loading of the page.

protected void Page_Load(object sender, EventArgs e)
{
      Blist = (List<string>)Session["items"];

      if (!Page.IsPostBack)
      {

         if (Blist != null)
         {
             ListBox1.Items.Clear();
             for (int i = 0; i < Blist.Count; i++)
                 ListBox1.Items.Add(Blist[i]);
         }
     }
 }

Upvotes: 4

Related Questions