Search code examples
c#asp.netsharepointsharepoint-2010comboboxlist

CheckBoxList ListItem Count always 0 after adding data dynamically


I have the following code in aspx code. I wanted to add ListItem check boxes to ColumnsList and Find all the checked one's on button click.

But when I try to get the selected items on button click the ColumnsList count becomes 0.

<asp:checkboxlist runat="server" EnableViewState="true" id="ColumnsList"/>

In code behind I add data to my ColumnsList as follows

public override void OnLoad()
{
    if(!this.IsPostBack)
    {
       this.ColumnsList.Items.Add(new ListItem { Text= "Text1",  Value = "value1"    });
       this.ColumnsList.Items.Add(new ListItem { Text= "Text2",  Value = "value2"  });
    }
}

// Here is the button click listener

private void Button_Click(object sender, EventArgs eventArgs)
{
    // Count is 0 instead of 2
    var count = this.ColumnsList.Items.Count;
    foreach(ListItem item in this.ColumnsList.Items)
    {
        var selected = item.Selected;
        // add selected to a list..etc

    }
}           

Note: The application is Deployed in share point 2010.


Solution

  • I ended up moving the code which loads the List from pageload to OnInit as follows and it worked.

    protected override void OnInit(EventArgs e)
    {
      this.ColumnsList.Items.Add(new ListItem { Text= "Text1",  Value = "value1"    });
      this.ColumnsList.Items.Add(new ListItem { Text= "Text2",  Value = "value2"  });
    

    }