David Tunnell
David Tunnell

Reputation: 7532

Programmatically adding dynamically named checkboxes

I am programmatically trying to add a checkbox with a unique ID to a div:

        foreach (var item in tweetList)
        {
            Panel tweetPanel = new Panel();
            tweetPanel.BorderColor = System.Drawing.Color.Black;
            tweetPanel.BorderWidth = 1;
            tweetPanel.Attributes["style"] = "padding: 20px; margin 20px; width: 20%;"; 
            tweets.Controls.Add(tweetPanel);
            CheckBox tweetChecker = new CheckBox();
            tweetChecker.ID = "checkBox" + count;
            tweetPanel.Controls.Add(tweetChecker);
            tweetPanel.Controls.Add(new LiteralControl("<img src=\"" + item.profileImageUrl + "\">"));
            count++;
        }

in this div:

    <div id="tweets" runat="server">
    </div>

But when I run it it says:

Control 'checkBox0' of type 'CheckBox' must be placed inside a form tag with runat=server.

Why wouldn't a programmatically created check box not be considered server side? And how do I fix this

Upvotes: 1

Views: 457

Answers (1)

Gilles
Gilles

Reputation: 5407

The controls need to be inside a form element so that they can be posted to the server when the form is submitted.

<form id="myForm" runat="server">
    <!-- your controls -->
    <div id="tweets" runat="server">
    </div>
</form>

You can only add controls outside of a form element if those controls do not cause a postback.

Upvotes: 1

Related Questions