locked
ListControl added as child controls does remember selected items on postback RRS feed

  • Question

  • User-825949172 posted

    Hi

    I am get very frustrated while added listcontrol inside my custom server control. Basically, these controls does not remember what items user selected when postback occurs.

    Just to test this I have created following code. Checkboxlist remembers its items collection but for some bizzare reason does not remember checked items when postback occurs. Please can someone provide me solution or direct me to correct resource;

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Linq;
    using System.Text;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace AspNetServerControls
    {
    	[ToolboxData("<{0}:TestingViewStates runat=server></{0}:TestingViewStates>")]
    	public class TestingViewStates : WebControl
    	{
    		protected override void CreateChildControls()
    		{
    			CheckBoxList chkList = new CheckBoxList();
    			chkList.EnableViewState = true;
    			Controls.Add(chkList);
    
    			if (chkList.Items.Count == 0)
    			{
    				List<string> items = new List<string>();
    				items.Add("London");
    				items.Add("New York");
    				items.Add("Paris");
    
    				chkList.DataSource = items;
    				chkList.DataBind();
    			}
    			
    			base.CreateChildControls();
    		}
    	}
    }
    


     

    Saturday, July 4, 2009 12:35 PM

Answers

  • User1282917655 posted

    you need to add the items in the Render Method not inthe CreateChildControls.

    just move the listitems parts to be in the Render Method.

    Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
    
     End Sub



    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, July 5, 2009 4:38 AM