【问题标题】:Control '0' of type 'TextBox' must be placed inside a form tag with runat=server“TextBox”类型的控件“0”必须放在带有 runat=server 的表单标记内
【发布时间】:2012-12-08 12:22:30
【问题描述】:

我创建了一个动态表(在服务器端),列是(irem、price、pic 和 textxbox), 当我尝试添加文本框时,我得到消息 Control '0' of type 'TextBox' must be placed inside a form tag with runat=server .

这里是代码(案例 4 是我创建文本框的地方):

  protected void createTable()
{
    int numberOfItems = mylist.Count;



    // Create a new HtmlTable object.
    HtmlTable table1 = new HtmlTable();

    // Set the table's formatting-related properties.
    table1.Border = 1;
    table1.CellPadding = 1;
    table1.CellSpacing = 1;
    table1.BorderColor = "red";

    // Start adding content to the table.
    HtmlTableRow row;
    HtmlTableCell cell;
    for (int i = 0; i < numberOfItems; i++)
    {
        // Create a new row and set its background color.
        row = new HtmlTableRow();
        row.BgColor = "lightyellow";
        row.Height = Convert.ToString(100);


        name = mylist[i].Name;
        price = mylist[i].Price;
        image = mylist[i].ImagePath;




        for (int j = 1; j <= 4; j++)
        {
            // Create a cell and set its text.
            cell = new HtmlTableCell();




            switch (j)
            {
                case 1:
                    cell.InnerHtml = name;
                    break;
                case 2:
                    cell.InnerHtml = Convert.ToString(price);
                    break;
                case 3:
                    cell.InnerHtml = image;
                    break;
                case 4:
                    TextBox txt = new TextBox();
                    txt.ID = Convert.ToString(i);
                    txt.TextMode = TextBoxMode.SingleLine;
                    txt.Attributes.Add("runat", "server");
                    cell.Controls.Add(txt);
                    break;
                default:

                    break;


            }

            // Add the cell to the current row.

            row.Cells.Add(cell);
        }

        // Add the row to the table.
        table1.Rows.Add(row);
    }

    // Add the table to the page.
    this.Controls.Add(table1);

}

【问题讨论】:

    标签: asp.net


    【解决方案1】:

    关于您的问题,正如错误所说,所有具有runat=server 的控件都必须放在具有runat=server 标签的表单中。 在您的情况下,您将使用以下行将表(具有服务器端 Textbox)添加为页面中的 根元素

    this.Controls.Add(table1);
    

    相反,您应该将其添加为元素 &lt;form&gt;&lt;/form&gt; 标记。 这可以通过在主表单中添加一个 id 属性来轻松完成(例如,在您的 aspx 页面中添加 &lt;form runat="server" id="myForm"&gt;,然后使用 this.Controls.Add() 代替:

    myForm.Controls.Add(table1);
    

    或者,只需在您的 aspx 页面中的某处放置一个空的 divrunat=server
    (例如&lt;div id=myDiv runat=server /&gt;)并将表格添加到该div:

    myDiv.Controls.Add(table1);
    

    【讨论】:

    • 我有同样的问题,但我试图以编程方式呈现一个 ASCX 文件,其中包含 Web 服务中的服务器端控件。如何以编程方式将 DIV 添加到我的页面,以便我可以向其中添加服务器端控件?
    猜你喜欢
    • 2012-10-09
    • 1970-01-01
    • 2011-01-30
    • 2015-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-25
    • 2017-08-27
    相关资源
    最近更新 更多