adding a textbox run time gives error

B

Beatrix

Dear All,

I have checked many places but couldn't find the error in this script.
Error is:

"Control 'YourAnswer' of type 'TextBox' must be placed inside a form tag
with runat=server"



Code:

private void Load_Controls()
{
TextBox txtYourAnswer = new TextBox();
txtYourAnswer.ID = "YourAnswer";
txtYourAnswer.Text = "";
Controls.Add(txtYourAnswer);
}

if I add:
HtmlForm f =FindControl("form1");

and change last row to f.Controls.Add(txtYourAnswer);

I get:

Error 1 Cannot implicitly convert type 'System.Web.UI.Control' to
'System.Web.UI.HtmlControls.HtmlForm'. An explicit conversion exists (are you
missing a cast?) D:\Projects\QuizFolder\Quiz3\Q1.aspx.cs 33 21 D:\...\Quiz3\

Thank you for your help,
 
D

D.Dark

The FindControl method returns a Control object. Even if the control is a
Form it is still a Control object and not a Form. You have to convert it to a
Form like this:

HtmlForm f = (HtmlForm)FindControl("form1");
 
B

Beatrix

Thankyou that worked. Can U please explain, why textbox is not working like
label? What is the meaning of this mess with htmlform and findcontrol?

If I put all my controls in this htmlform, like radiobuttons, etc it will
always work?

Thank you,
 
R

Riki

Beatrix said:
Thankyou that worked. Can U please explain, why textbox is not
working like label? What is the meaning of this mess with htmlform
and findcontrol?

If I put all my controls in this htmlform, like radiobuttons, etc it
will always work?

A textbox has to be inside a form tag with the runat="server" attribute.
You can test this out by adding a textbox to your page in the editor, but
placing it outside the form tag.
You will get the same error as you did before.

The problem with your previous code was that you use:
Controls.Add(txtYourAnswer)
This is the same as:
Page.Controls.Add(txtYourAnswer)

This means that your textbox will be added AFTER all the other controls,
i.e. after the form tag (even after the closing body tag).
Which is causing the error.

When you use f.Controls.Add(myTextbox), it will be added after all the
controls INSIDE the form tag.

Hope this helps you understand.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,228
Members
46,818
Latest member
SapanaCarpetStudio

Latest Threads

Top