Instead of directly entering the code, as you are trying now, you can add a user control to your ItemTemplate and execute your code in a user control. The code will dynamically create the required ASP.NET controls and add them to the user control. Collection of teams.
Thus, you will have the best of both worlds: the execution of dynamic code and (since user control is involved in the life cycle of the page) the correct formation of HTML.
UPDATE
Here is an example. Say you created a user control called "WebUserControl2.ascx" and added it to your home page:
<%@ Register src="WebUserControl2.ascx" tagname="WebUserControl2" tagprefix="uc1" %>
Then you can add it to your DataList ItemTemplate:
<asp:DataList runat="server" ID="DataList1"> <ItemTemplate> <uc1:WebUserControl2 ID="MyWebUserControl" runat="server" /> </ItemTemplate> </asp:DataList>
And in your WebUserControl2.ascx.cs code for managing web users, you add a shortcut, text box and button:
protected void Page_Load(object sender, EventArgs e) { Label Label1 = new Label(); Label1.ID="Label1"; Label1.Text = "Please enter info: "; this.Controls.Add(Label1); TextBox Textbox1 = new TextBox(); Textbox1.ID="Textbox1"; this.Controls.Add(Textbox1); Button Button1 = new Button(); Button1.ID = "Button1"; Button1.Text = "Submit"; this.Controls.Add(Button1); }
When the page starts up and the DataList is bound, you will get something like:

You can add properties to the user control and assign their values ββfrom the main page, for example, the DataList ItemCreated event, so the control will know which item is currently being created and is acting accordingly.
source share