How to Create a Background Color in a Web Page From ASP.NET
Changing the background color on an ASP.NET Web page enables you to set the page's mood to reflect its contents. A tranquil blue background, for example, may work well on a meditation site. A flamingo pink color might bring a floral site to life. Browsers, by default, display white backgrounds on ASP.NET Web pages when users view them. To create a different background color, use the ASP.NET "Attributes" class to customize your page's "body" element.
Instructions
-
-
1
Launch Visual Studio. Click "File," "New" and then click "Project."
-
2
Click the "Visual C#" button, and then double-click "ASP.NET Web Application" to create a new Web application. Its files appear in the Solution Explorer window.
-
-
3
Click the "Project" button at the top of Visual Studio and then click "Add New Item." Double-click "Web Form." Visual Studio adds a new form named "WebForm1.aspx" to the Solution Explorer.
-
4
Click "WebForm1.aspx" to highlight it. Locate the set of buttons in the bottom-left corner of the user interlace and click the "Design" button. The Design window opens and displays a blank form.
-
5
Click "Toolbox" in the menu. Double-click the "Button" control in the Toolbox window. Visual Studio places a button named "Button1" on the empty form.
-
6
Double-click "Button1." The code window opens and displays the button's "Click" event method:
protected void Button1_Click(object sender, EventArgs e)
{
}
-
7
Replace that code with this code:
protected void Button1_Click(object sender, EventArgs e)
{
Body.Attributes["bgcolor"] = "Blue";
}
This uses the ASP.NET "Attributes" class to assign blue as the background color for the element whose ID is "Body." That element does not exist yet.
-
8
Click the "WebForm1.aspx" file located in the Solution Explorer to view the form's HTML code. Locate the <body> tag within that code. It looks like this:
<body>
Replace that with the following:
<body id="Body" runat="server">
This adds the "Body" id value needed by the "Attributes" class shown in the previous step.
-
9
Press "F5" to run the project. The ASP.NET page opens in your browser and displays the button you added. Click the button to change the background color to blue.
-
1
Tips & Warnings
This example illustrates changing the page background color using a button click. You could also place the "Body.Attributes" statement in other locations, such as the page's "Load" event. Doing so causes the color to change when a user opens the page.