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;
}
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.IsPostBackis 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.