0

I'm creating a button and adding it to a panel

        Panel p = new Panel();
        p.ID = "b_con";
        p.Attributes.Add("runat", "server");
        this.Controls.Add(p);
        Button b = new Button();
        b.Attributes.Add("value", "reply");
        b.Attributes.Add("id", Convert.ToInt32(r["Message_ID"]).ToString());
        b.Attributes.Add("class", "button");
        b.Click += new System.EventHandler(button_Click);
        p.Controls.Add(b);

I got this error Control 'ctl01' of type 'Button' must be placed inside a form tag with runat=server.

3
  • Panels are server controls. You don't need to add runat="server". A Button has an Id and a Text property. Commented Oct 4, 2012 at 20:18
  • 1
    At what point do you add the panel to a page? Commented Oct 4, 2012 at 20:20
  • Was your problem solved? Commented Oct 4, 2012 at 23:06

2 Answers 2

3

The page you are adding it to needs to have this on it. And your panel must live within the form tags.

<body>
<form runat="server">

<!-- Panel must be added within here -->
<div id="messages_con">
    <asp:Panel id="b_con" runat="server" />
</div>

</form>
</body>

So the panel you add it to needs to be in your Html Code. You are adding a button to a panel that doesn't exist on the page. Instead, reference the panel in the Html (as seen above), like this:

Panel p = b_con;
//p.ID = "b_con";
//p.Attributes.Add("runat", "server"); -- Not necessary
this.Controls.Add(p);
Button b = new Button();
b.Attributes.Add("value", "reply");
b.Attributes.Add("id", Convert.ToInt32(r["Message_ID"]).ToString());
b.Attributes.Add("class", "button");
b.Click += new System.EventHandler(button_Click);
p.Controls.Add(b);
Sign up to request clarification or add additional context in comments.

8 Comments

The problem is that I'm creating the whole thing in the behind code .. how can I make the runat server form within the behind code?
Are you saying you don't have a Web page that you are putting this on?
I have a web page but all of its contents coming from the behind code, because the panels & the buttons are depending on database results. I can change the way that I'm using to do this, but I a newbie to ASP and obviously I don't know how .. :
What do you mean by ALL of its contents? You do have a <body> tag, yes?
I have a body tag .. and I have in it <div id="messages_con"></div> and I change the div contents from my behind code using InnerHtml
|
0

Use Form.Controls.Add(p);

by using this we can add panel on form tag.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.