Unlike Web controls, HTML elements can not, by default, be controlled programmatically. However, you can convert an HTML element to a server control and then write code to access or modify the element. Most of the HTML elements that appear in the Tool Palette can be converted by using the Run As Server Control command. HTML elements that do not appear on the Tool Palette, such as body, can be converted manually.
The following procedures explain how to convert an HTML table element by using the Run As Server Control command, and how to convert a body element manually.
To convert an HTML table element to a server control
- With an ASP.NET application open, display the Designer.
- From the Tool Palette, add the HTML Table element from the HTML Elements category to the Designer.
- Right-click the Table element on the Designer and choose Run As Server Control. The server control icon is added to the Table element. In the .aspx file, the id="TABLE1" and runat="server" attributes are added to the table tag. In the code-behind file, TABLE1 is declared using System.Web.UI.HtmlControls.HtmlTable.
- You can now reference TABLE1 in your code. To demonstrate this, add a Button from the Web Controls category of the Tool Palette to the Designer.
- Double-click the button. The Code Editor opens and is positioned at the click event for the button.
- Add the following code to the event handler to change the background color of the table to blue. Note that TABLE1 is the id that was added automatically to the the table tag in Step 3.
TABLE1.BgColor := 'blue';
- Choose RunRun to run the application.
- Click the button to change the table color.
To convert an HTML body element to a server control manually
- With an ASP.NET application open, display the .aspx file.
- Add the runat="server" and id="identifier" attributes to the body tag, where identifier is a descriptive identifier, such as bodytag.
- Add the following declaration to the strict protected section of the code-behind file:
bodytag: System.Web.UI.HtmlControls.HtmlGenericControl;
protected System.Web.UI.HtmlControls.HtmlGenericControl bodytag;
- You can now reference bodytag in your code. To demonstrate this, add a Button from the Web Controls category of the Tool Palette to the Designer.
- Double-click the button. The Code Editor opens and is positioned at the click event for the button.
- Add the following code to change the background color of the Web Form to yellow.
bodytag.Attributes['bgcolor'] := 'yellow';
bodytag.Attributes["bgcolor"] = "yellow";
- Choose RunRun to run the application.
- Click the button to change the background color of the form.