Yesudass Moses
Yesudass Moses

Reputation: 1859

using Viewstate for ListItemCollection in WebUserControl

I am developing a UserControl which uses a ListItemCollection member. I can add Items to this ListItemCollection, but It is cleared after a postback. How can I use a viewstate with it.

    public partial class IgList : System.Web.UI.UserControl
    {
        public ListItemCollection Items = new ListItemCollection();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                Items = new ListItemCollection();
            }
        }

        public void fillList()
        {
            int i = 1; 

            foreach (ListItem li in Items)
            {
                LinkButton lb = new LinkButton();
                lb.ID = "IgListItem" + i; 
                lb.Style.Add("clear", "both");
                lb.Style.Add("display", "block");
                lb.Style.Add("width", "100%");
                lb.Style.Add("height", "23px");
                lb.Font.Underline = false; 
                lb.ForeColor=  System.Drawing.Color.Black; 
                lb.Height= Unit.Pixel(23); 
                lb.BorderColor= System.Drawing.Color.Gainsboro;  
                lb.BorderStyle= BorderStyle.Solid;
                lb.BorderWidth = Unit.Pixel(1);
                lb.Text = li.Text;
                lb.CommandArgument = li.Value;
                lb.CommandName = "ItemSelected"; 
                i++;
                Panel1.Controls.Add(lb);

            }
        }
    }
}

Upvotes: 0

Views: 184

Answers (1)

MaCron
MaCron

Reputation: 121

Take Items = new ListItemCollection(); out of !Page.IsPostBack having it in there will only put data in Items on the first page load. If you really want to use a view state you can, you can set it on initial page load, where you are now, and set the control out side of that block, wither way will accomplish the same thing. I prefer the first method in case the data has changed since the last ViewState was set.

Upvotes: 1

Related Questions