0

私は 2 つのボタンとListBox. 最初のボタンをクリックすると、選択したアイテムが削除されるはずですListBoxが、そうではありません-ListBox同じままです。コードの何が問題になっていますか?

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;
}
4

1 に答える 1

4

ページがポストバックされると (ボタンがクリックされると)、Page_Load ハンドラーが再び起動します。これを行うと、リストが再作成されます。これを防ぐには、ページ ポスト バックか初期ロードかを確認する必要があります。Page.IsPostBackこれを行うには、が true か falseかを確認します。true の場合、ページが (ボタンのクリックなどによって) ポストバックされていることを意味します。そうでない場合は、ページの初期読み込みを意味します。

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]);
         }
     }
 }
于 2012-12-10T18:12:32.563 に答える