there is dynamic table that i created(on server-side), the cols is(irem,price, pic and textxbox),
when i try to add the textbox i getting the messege Control '0' of type 'TextBox' must be placed inside a form tag with runat=server
.
here is the code (case 4 is where i create the textbox ):
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);
}
Best Answer
Regarding your question, as the error says, all controls that have the
runat=server
must be placed inside a form that has therunat=server
tag too. In your case, you're adding the table (which has a server-sideTextbox
) as a root element in your page, using this line:Instead, you should add it as an element inside the
<form></form>
tag. This can easily be done by either adding an id attribute to your main form (e.g.<form runat="server" id="myForm">
in your aspx page and then, instead ofthis.Controls.Add()
use:Or, just put an empty
div
withrunat=server
somewhere in your aspx page(e.g.
<div id=myDiv runat=server />
) and add the table to that div: