.netCoders Contact Us
Search:

Adding Controls

Using server controls, you can assemble ASP.NET forms quickly and have access to an efficient programming model. Visual Studio.NET collects the available controls onto the Toolbox. Using this menu, you can drag and drop elements onto your form.

Setting Properties

Properties can be set by either right-clicking on a control in design mode and selecting Properties from the context menu, or programmatically. If you open the code-behind file for a form, you'll see that each web form element is declared as a protected data member. Using this object, you can set properties and call methods.

Loading Controls Dynamically

Controls can also be added programmatically. The Page object, as well as container objects such as the Panel, contain a Controls collection. Using the Add method, you can add a control at run time. To load a control from an ascx file, use the Page object's LoadControl method, and pass it the virtual path to the control. For example, the following code dynamically creates an instance of a header control, sets some properties, and then adds the control to a Panel placeholder.
DotnetCoders.Web.Header ctlHeader = (DotnetCoders.Web.Header) this.LoadControl(SiteConfig.RootURL + "Framework/Header.ascx");
ctlHeader.PageTitle = objArticle.Title;
ctlHeader.Description = objArticle.Description;
ctlHeader.Keywords = objArticle.Keywords;
pnlHeader.Controls.Add(ctlHeader);

Using Stylesheets

To add a stylesheet to an ASP.NET page, use the standard HTML methods for including styles.

1. Inline Styles - Many of the .NET server controls implement a CssClass attribute for indicating the style sheet. When the control is rendered, the runtime will convert this attribute into an HTML class attribute. You also can add style attributes to the controls, and they will carry through to the rendered HTML.

2. Page Styles - Using the HTML <style> tag, you can include styles within an ASP.NET page. Here is an example style within an ASP.NET page:

<%@ Page language="C#" %>
<html>
<head>
     <style type="text/css">
     <!--
     BODY {font: 10pt}
     -->
     </style>
</head>
<body>
</body>
</html>

3. Stylesheet Files Styles can also be created as separate .css files, and included in an ASP.NET page using the <link> tag.

<link rel=stylesheet href="style.css" type="text/css">