Search code examples
kenticoform-control

How to save custom form control input data in web part?


I followed the "Developing Custom Form Control" in kentico documentation and built a custom list box. I added the list box dynamically on the code behind and NOT adding it directly on the code front (ascx). I use the list box on one of my web parts and everything works well when I selected multiple items. However, when I click to edit the web part, all of the selected items are gone and the the list box comes back to its original form ( no item selected ). Therefore, I wonder how kentico save the old data of the form control in the web part.

On the code below, I recreate my scenario with a short version. I dynamically add the list box under a panel.

protected void EnsureItems()
  {
      // Create item and list box
      ListBox tab = new ListBox(); 

      ListItem item = new ListItem();
      item.Text = "test";

      tab.Items.Add(item);
      panel.Controls.Add(tab);
  }


protected void Page_Load(object sender, EventArgs e)
  {
      EnsureItems();
  }

Solution

  • Each Form Control should be inherited from FormEngineUserControl. And Kentico utilizes Value property then to store and retrieve values from the db. Here is the example:

    public override object Value
    {
        get
        {
            return listBox.SelectedValue;
        }
    
        set
        {
            listBox.SelectedValue = ValidationHelper.GetString(value, string.Empty);
        }
    }
    

    Basically, your getter should return some value to be stored in the database. And in the setter you should initialize your listbox, fill with data and make a selection base on value coming from the database.