Het aanroepen van Controls in .Net kent volgende fasen:
Met Visual Studio .net kan je op een eenvoudige manier User Controls in een project aanmaken:
Toon /verberg sourcecode
De Page directive Register wordt gebruikt om een control te registeren op een webpagina. Nu kan je zoveel instanties van de Control Kalender op de Web Form gebruiken als je wil.

Toon /verberg sourcecode
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Kalender : System.Web.UI.UserControl
{
protected void Page_Load(object sender, System.EventArgs e)
{
TxtDatum.Style["Text-align"] = "right";
}
protected void BtnSelecteer_Click(object sender, System.EventArgs e)
{
Kal.Visible = !Kal.Visible;
}
protected void Kal_SelectionChanged(object sender, System.EventArgs e)
{
TxtDatum.Text = Kal.SelectedDate.ToShortDateString();
Kal.Visible = false;
}
}
Inloggen.ascx <%@ Control Language="C#" AutoEventWireup="true" CodeFile="Inloggen.ascx.cs" Inherits="Inloggen" %> <style type="text/css"> .UCLogin { BORDER: 1px solid <%= RandKleur %> } </style> <table class="UCLogin"> <tr> <td> <asp:Label ID="Label1" runat="server" Text="Gebruikersnaam"></asp:Label></td> <td style="width: 158px"> <asp:TextBox ID="TxtGnaam" runat="server"></asp:TextBox></td> </tr> <tr> <td> <asp:Label ID="Label2" runat="server" Text="Paswoord"></asp:Label></td> <td style="width: 158px"> <asp:TextBox ID="TxtPwd" runat="server" TextMode="Password"></asp:TextBox></td> </tr> <tr> <td> </td> <td style="width: 158px"> <asp:Button ID="BtnInloggen" runat="server" Text="Inloggen" OnClick="BtnInloggen_Click" /></td> </tr> </table>
Je merkt dat we met CSS een opmaak voorzien voor de tabel die de controls omvat. De waarde van de eigenschap RandKleur wordt runtime in de CSS-klasse UCLogin ingegeven.
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Inloggen : System.Web.UI.UserControl
{
private string randkleur;
public string RandKleur
{
get { return randkleur; }
set { randkleur = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (TxtGnaam.Text == "")
{
TxtGnaam.Text = "Naam a.u.b.";
TxtGnaam.Attributes["onclick"] = "this.value=''";
}
else
{
TxtGnaam.Attributes["onclick"] = "void(0)";
}
}
}
InlogScherm.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeFile="InlogScherm.aspx.cs" Inherits="InlogScherm" %> <%@ Register Src="Inloggen.ascx" TagName="Inloggen" TagPrefix="uc1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <uc1:Inloggen ID="Inloggen1" runat="server" RandKleur="red" /> </div> </form> </body> </html>
In de voorgaande voorbeelden hebben we een User Control gemaakt door bestaande Controls te gebruiken en samen te brengen tot een grotere control.
Dergelijke controls worden opgeslagen in een ascx-bestand binnen je Web Site.
Je kan Custom Controls maken door over te erven van een bestaande control.
Dergelijke controls huizen in een Control Library en worden gecompileerd in een assembly.
We maken een control die overerft van een gewone TextBox en zorgen ervoor dat wanneer de eigenschap Enabled op false staat, de TextBox als gewone tekst wordt getoond (zonder kadertje).
TextBoxSpeciaal.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace MijnControls { [DefaultProperty("Text")] [ToolboxData("<{0}:TextBoxSpeciaal runat=server>{0}:TextBoxSpeciaal>")] public class TextBoxSpeciaal : TextBox { [Bindable(true)] [Category("Appearance")] [DefaultValue("")] [Localizable(true)] public string LabelCSS { get { return ((string)ViewState["LabelCSS"]); } set { ViewState["LabelCSS"] = value; } } protected override void Render(HtmlTextWriter output) { if (!this.Enabled) { //toon enkel de tekst output.Write(@"{1}", this.LabelCSS, this.Text); } else { //render volgens de normale manier base.Render(output); } } } }
GebruikTextBoxSpeciaal.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeFile="GebruikTextBoxSpeciaal.aspx.cs" Inherits="GebruikTextBoxSpeciaal" %> <%@ Register Assembly="MijnControls" Namespace="MijnControls" TagPrefix="cc1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> <style type="text/css"> .rood {background-color:red;color:yellow} </style> </head> <body> <form id="form1" runat="server"> <div> <cc1:textboxspeciaal id="TxtTest" runat="server" LabelCSS="rood"></cc1:textboxspeciaal> <br /> <asp:Button ID="BtnToggleEnabled" runat="server" Text="Disable" OnClick="BtnToggleEnabled_Click" /></div> </form> </body> </html> GebruikTextBoxSpeciaal.aspx.cs ... protected void BtnToggleEnabled_Click(object sender, EventArgs e) { TxtTest.Enabled = !TxtTest.Enabled; if (TxtTest.Enabled) BtnToggleEnabled.Text = "Disable"; else BtnToggleEnabled.Text = "Enable"; } ...
We maken nog een Custom Control: een uitklapbare box met titel en inhoud.
De pagina houdt met cookies bij wat de status van elke box is.
CustomBox.bmp
CustomBox.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
namespace MijnControls
{
[DefaultProperty("Text")]
[ToolboxData("<{0}:CustomBox runat=server></{0}:CustomBox>")]
public class CustomBox : WebControl
{
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
#region "vars en properties"
private string inhoud;
private string titel;
private static Unit breedte;
private bool open;
// eigen volgnr van de control
private int volgnr;
// aantal aangemaakte CustomBoxen
private static int aantal = 0;
public CustomBox()
{
aantal++;
volgnr = aantal;
}
/// De tekst die in de box moet verschijnen,
/// kan zichtbaar en onzichtbaar worden gemaakt
public string Inhoud
{
get { return inhoud; }
set { inhoud = value; }
}
/// De titel voor een box,
/// wordt steeds getoond
public string Titel
{
get { return titel; }
set { titel = value; }
}
/// Aangeven met een boolean of de inhoud moet worden weergegeven
/// bij openen van de pagina
public bool Open
{
get { return open; }
set { open = value; }
}
/// Breedte van de CustomBox
public override Unit Width
{
get { return breedte; }
set { breedte = value; }
}
/// Breedte van de CustomBox
private int Aantal
{
get { return aantal; }
set { aantal = value; }
}
#endregion
#region "methoden"
private StringBuilder MaakCode()
{
StringBuilder sb = new StringBuilder();
sb.Append("");
if (volgnr == 1)
{
//stijlblok toevoegen
sb.Append("<style> "
+ "BODY { margin: 10px 10px 10px 10px; }"
+ ".CustomBox { width: " + Width + "; border-width: 0px; }"
+ ".CustomBox .Hoofd { height: 25px; background-color: #CCCCCC; "
+ "color: #6699CC; font-weight: bold; font-size: x-small; "
+ "font-family: verdana, arial, helvetica; }"
+ ".CustomBox .Hoofd TD { border-top: solid 1px #6699CC; "
+ "border-bottom: solid 1px #6699CC; }"
+ ".CustomBox .Hoofd .Hoekcel { border-top: solid 0px #6699CC; }"
+ ".CustomBox .Inhoud { color: Black; font-size: x-small; "
+ "font-family: verdana, arial, helvetica; }"
+ ".CustomBox .Inhoud TD { border-bottom: solid 1px #6699CC; "
+ "border-left: solid 1px #6699CC; border-right: solid 1px #6699CC; }"
+ ".HandCursor { cursor: hand; }"
+ ".Text { }"
+ "</style>");
// Javascript functies toevoegen
sb.Append("<script language=javascript>"
+ "function Boxinhoud( obj, cbid )"
+ "{"
+ "var inhoudBox = document.getElementById('Inhoud' +cbid );"
+ "var datum = new Date();"
+ "datum.setDate(datum.getDate()+5);"
+ "if ( inhoudBox.style.display == 'none' )"
+ "{ "
+ "inhoudBox.style.display = 'block';"
+ "obj.src = 'images/CustomBox_sluit.gif';"
+ "setCookie(cbid,'true',datum);"
+ "}else{"
+ "inhoudBox.style.display = 'none';"
+ "obj.src = 'images/CustomBox_open.gif';"
+ "setCookie(cbid,'false',datum);"
+ "}"
+ "}"
+ "function setCookie(name, value, expires)"
+ "{"
+ "document.cookie= name + '=' + escape(value) +"
+ "((expires) ? '; expires=' + expires.toGMTString() : '')"
+ "}"
+ "</script>");
}
return sb;
}
private StringBuilder MaakKop(string breedte, string titel)
{
StringBuilder sb = new StringBuilder();
sb.Append("<table id='" + this.ID + "'class='CustomBox' cellpadding='0' cellspacing='0'>"
+ "<tr class='Hoofd'>"
+ "<td width='1%' align='left' class='Hoekcel'>"
+ "<img src='images/CustomBox_linkerhoek.gif'>"
+ "</td>"
+ "<td width='97%'>"
+ "<span>" + Titel + " </span>"
+ "</td>"
+ "<td width='1%'>"
+ "<img src='images/CustomBox_"
+ (Open ? "sluit.gif" : "open.gif")
+ "' class='HandCursor' onclick='Boxinhoud( this, \"" + this.ID + "\" )'>"
+ "</td>"
+ "<td width='1%' align='right' class='Hoekcel'>"
+ "<img src='images/CustomBox_rechterhoek.gif'>"
+ "</td>"
+ "</tr>"
+ "</table>");
return sb;
}
private StringBuilder MaakInhoud()
{
StringBuilder sb = new StringBuilder();
sb.Append("<table id='Inhoud" +this.ID +"' class='CustomBox' "
+"cellpadding='0' cellspacing='0' style='display: "
+ (Open ? "block" : "none") + "';>"
+ "<tr class='Inhoud'>"
+ "<td><!-- Inhoud Begin -->");
return sb;
}
private StringBuilder MaakVoet()
{
StringBuilder sb = new StringBuilder();
sb.Append("<!-- Inhoud Einde --></td></tr></table>");
return sb;
}
protected override void Render(HtmlTextWriter output)
{
for (int i = 0; i < Page.Request.Cookies.Count; i++)
{
HttpCookie cookie = Page.Request.Cookies[i];
if (cookie.Name.Equals(this.ID) == true)
{
Open = Convert.ToBoolean(cookie.Value);
}
}
output.Write(
MaakCode().ToString()
+ MaakKop(Width.ToString(), Titel).ToString()
+ MaakInhoud().ToString()
+ Inhoud
+ MaakVoet().ToString());
}
public override void Dispose()
{
Aantal = 0;
base.Dispose();
}
#endregion
}
}
Opmerking: zoals je merkt moet je ervoor zorgen dat de figuren beschikbaar zijn in je Web Site. Het is daardoor meestal handig ervoor te zorgen dat Custom Controls "self-contained" zijn en geen externe bestanden nodig hebben. Maar ja, het is eens leuk iets met figuurtjes te doen :)
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GebruikCustomBox.aspx.cs" Inherits="GebruikCustomBox" %>
<%@ Register Assembly="MijnControls" Namespace="MijnControls" TagPrefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Inhoud</h2>
<table cellspacing="10" border="0">
<tr>
<td valign="top"><cc1:CustomBox id="CustomBox1" runat="server" Width="150px" Inhoud="Leve ASP.net<br>Volg ASP.net aan het <a href='http://www.ivobrugge.be/cursusweb'>IVO Brugge</a>"
titel="ASP.net" Open="True"></cc1:CustomBox></td>
<td valign="top"><cc1:CustomBox id="CustomBox2" runat="server" Width="150px" Inhoud="Leuk hoor, werken met Custom Controls"
titel="Control"></cc1:CustomBox>
<p></p>
</td>
</tr>
<tr>
<td valign="top"><cc1:CustomBox id="Custombox3" runat="server" Width="150px" Inhoud="Leve Java<br>Volg Java aan het <a href='http://www.ivobrugge.be/cursusweb'>IVO Brugge</a>"
titel="Java" Open="True"></cc1:CustomBox></td>
<td valign="top"><cc1:CustomBox id="Custombox4" runat="server" Width="150px" Inhoud="Dit is een server-side Custom Box"
titel="<span style='color:red'>Belangrijk</span>" Open="true"></cc1:CustomBox>
<p></p>
</td>
</tr>
</table>
</div>
<br />
<asp:Button ID="Button1" runat="server" Text="PostBack" />
</form>
</body>
</html>
Composite Controls of samengestelde controls stellen je in staat meerdere controls te bundelen in één gecompileerde Custom control.
Hiertoe maak je een klasse voor je Control met volgende kenmerken:
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Drawing; // voor de bitmap
namespace MaakCompositeControl
{
/// <summary>
/// Summary description for TekstControl.
/// </summary>
[DefaultProperty("Text"),
ToolboxData("<{0}:TekstControl runat=server></{0}:TekstControl>"),
ToolboxBitmap(@"D:\William\WWW\Cursusweb\ASPNET\h7\MaakCompositeControl\TekstControl.bmp")
]
public class TekstControl : System.Web.UI.WebControls.WebControl, INamingContainer
{
[Bindable(true),
Category("Appearance"),
DefaultValue("")]
protected override void CreateChildControls()
{
LiteralControl lc = new LiteralControl("<h1>ASP.net Composite Control</h1>");
Controls.Add(lc);
TextBox txt = new TextBox();
Controls.Add(txt);
}
}
}
Je kan met VS.net ook een bitmap aanmaken voor later gebruik in de toolbox:
Je kan nu een ASP.net Web Application maken, de component op de toolbox plaatsen en gebruiken in een WebForm:
Het resultaat in HTML-weergave:
<%@ Register TagPrefix="cc1" Namespace="MaakCompositeControl" Assembly="MaakCompositeControl" %> <%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="GebruikCompositeControl.WebForm1" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <HTML> <HEAD> <title>WebForm1</title> <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" Content="C#"> <meta name="vs_defaultClientScript" content="JavaScript"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"> </HEAD> <body> <form id="Form1" method="post" runat="server"> <cc1:TekstControl id="TekstControl1" runat="server"></cc1:TekstControl> </form> </body> </HTML>
We kunnen vanuit een Composite control ook eigenschappen gebruiken. Hiermee kunnen we bijvoorbeeld eigenschappen van de deelcontrols aan de buitenwereld kenbaar maken.
We moeten er bij het aanspreken van de eigenschappen van de individuele controls wel zeker zijn dat ze reeds geplaatst werden in de composite control. We kunnen er voor zorgen dat de methode CreateChildControls zeker uitgevoerd is met de methode EnsureChildControls.
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Drawing;
namespace MaakCompositeControl
{
/// <summary>
/// Summary description for TabelControl.
/// </summary>
[DefaultProperty("Text"),
ToolboxData("<{0}:TekstControl runat=server></{0}:TekstControl>"),
ToolboxBitmap(@"D:\William\WWW\Cursusweb\ASPNET\h7\MaakCompositeControl\TekstControl.bmp")
]
public class TekstControl : System.Web.UI.WebControls.WebControl, INamingContainer
{
private string titel;
private TextBox txt;
public string Titel
{
get { return titel; }
set { titel = value; }
}
public string Tekst
{
get
{
EnsureChildControls();
return txt.Text;
}
set
{
EnsureChildControls();
txt.Text = value;
}
}
[Bindable(true),
Category("Appearance"),
DefaultValue("")]
protected override void CreateChildControls()
{
LiteralControl lc = new LiteralControl("<h1>" +Titel +"</h1>");
Controls.Add(lc);
txt = new TextBox();
Controls.Add(txt);
}
}
}
In een Web Application kunnen we nu de eigenschappen voor de Composite Control instellen:
<cc1:TekstControl id="TekstControl1" titel="Hoera!" tekst="invulveld" runat="server"></cc1:TekstControl>
| Meer tutorials: |
| leer ook: | html | | xhtml | | css | | asp | | asp.net | | c# | | ado.net | | linq | | ajax | | java | | javascript |