M. Carlo Bramini
M. Carlo Bramini

Reputation: 2522

adding listbox control programmatically and retaining Viewstate

My page has a button control.

When the button is clicked a listbox is added to a page's panel.

The problem is, at the first click a listbox appears, at the second or more clicks nothing happens, just the first list box is displayed.

I know the issue is probably with the viewstate, but I've no idea where to fix the code?

  public partial class _default : System.Web.UI.Page
    {
        List<ListBox> myList;


        protected void Page_Load(object sender, EventArgs e)
        {
            myList = new List<ListBox>();
            Button1.Click += Add_ListBox1;
        }

        public void Add_ListBox1(object sender, EventArgs e)
        {
            ListBox temp_listBox = new ListBox();
            myList.Add(temp_listBox);
            Panel1.Controls.Add(temp_listBox);
        }


    }

enter image description here

Upvotes: 0

Views: 248

Answers (2)

PATIL DADA
PATIL DADA

Reputation: 379

why don't u try this code as u said viewstate problem ... if it is this should work..

public partial class _default : System.Web.UI.Page
    {
 List<ListBox> myList;


    protected void Page_Load(object sender, EventArgs e)
    {
        myList = new List<ListBox>();
       Button1.Click += Add_ListBox1;
    }

    public void Add_ListBox1(object sender, EventArgs e)
    {
        int count = 1;


        if (ViewState["Clicks"] != null)
        {
            count = (int)ViewState["Clicks"] + 1;

            ListBox temp_listBox = new ListBox();
            myList.Add(temp_listBox);
            Panel1.Controls.Add(temp_listBox);

        }


        ViewState["Clicks"] = count;


    }

    protected void Button1_Click(object sender, EventArgs e)
    {

        Add_ListBox1(e,e);
    }
}

Upvotes: 0

Andrei Bozantan
Andrei Bozantan

Reputation: 3921

You need to understand the asp.net page lifecyle http://msdn.microsoft.com/en-us/library/ms178472(v=vs.85).aspx. On each button click the whole page will be recreated so your panel will be empty. Then the button click event handler is processed and just a listbox is added in the panel.

A possible solution to your problem is defined here http://www.codeproject.com/Articles/502251/How-to-create-controls-dynamically-in-ASP-NET-and.

Upvotes: 1

Related Questions