views:

37

answers:

4

I'm adding a dynamically built set of checkboxes to an asp.net page from the code behind with something like this in a recursive fashion:

pnlPageAccessList.Controls.Add(myCheckboxControl);

The controls show up fine on the page, but they don't show up when I view source, nor can I access them from the code behind. If I add the controls in the on_init method, they work. But I have some business rules driving changes to the list of controls itself that require I fire the add method elsewhere. Has anyone seen this before? I'm away from work so I can't copy the exact code.

I have two terrible ideas for how to get it working. One involves some jQuery and a set of hidden controls holding a big array of integers; the other is run the method on_init AND on my other events so the controls at least show up. Both smell like ugly hacks. The second one I suspect won't work to read the values out of the checkboxes.

+1  A: 

If you can set the ID for the checkbox controls you can use the FindControl method from code behind to retrieve the control instances.

Anero
+2  A: 

On the server side the page is recreated from scratch every postback, so if you add any controls dynamically, you have to re-add them on every postback.

As you add the controls at runtime they are not known at compile time, so there is no variables declared for the controls in the Page object. If you want to access the controls you either have to keep the reference from when you create the controls, or locate them in the Controls collection where you put them.

Guffa
+1  A: 

@Anero is right that you can add an ID and use FindControl.

You can also use a checkbox list, and add checkboxes to that list. Then they're already in a predefined control in your markup and code-behind.

You don't say where the method has to be fired, but once they're added dynamically, they do have to be added on every postback. You probably have a little more flexibility than just adding them at the Init event, as long as you stay aware of where things like validation occurs (if it matters in this case), or where you want to handle the checkbox contents. You can defer as late as PreRender for getting checkbox content.

Cylon Cat
A: 

Well, looks like I'm going to have to do it clientside. Thanks for the answers. I'd be able to do it On_Init, but doing it clientside with a hidden control is gonna save me a lot of overhead and be more flexible moving forward.

If anyone's curious, here's the jQuery for finding all the checked checkboxes and putting their value attribute into a hidden control in a comma delimited list:

<script type="text/javascript">
    $(document).ready(function () {
        $('[id*=PagesPanel]').find(':checkbox').click(function () {
            $('[id*=PagesPanel]').find(':checked').each(function () {
                $('[id*=lblHiddenPageArray]').append($(this).val() + ", ");
            });
        });
    });
</script>
fr0man