Creating Custom Web Controls in C # Stats (RPM)

Source: Internet
Author: User
Tags define empty iis split tostring microsoft iis
Web creating Custom Web Controls in C # Stats
rating:4.75 out of 5 by 4 users
Submitted:04/09/01


Peter Weng (lateboy@mit.edu)


--------------------------------------------------------------------------------


By have heard of ASP. NET ' s Web Controls. In this tutorial I plan to discuss the advantages of using Web Controls, as as, as and as, and deploy in C #.

What are Web Controls?

Web Controls are widgets that can is reused across multiple. Controls may render HTML to the client, or other formats such as WML or XML. If you are familiar with asp.net, you'll know that ASP.net provides some to right out of the box. These include datagrids, calendars, adrotators, etc.

Why use User Controls?

The biggest advantage of Web Controls is code reuse. Because they can be reused across multiple pages in different ways, Web Controls can save for you hassle of writing R HTML on multiple pages by generating the appropriate HTML for you.

But Why use C #? Can ' t we just use. ascx files?
. ascx files are another way of creating reusable controls. However, it doesn ' t always provide a clean way of separating the code from content. What This means be that content developers can write content, graphic artists and UI experts can layout your site, and Can develop the logic behind everything without overlapping each of the other. In addition, when deploying your Web site or giving your the Web site to someone else, by using the controls in C # and Pre -compiled, you won ' t have to give them any of your source code to launch your site, all you need to give them the DLL ' s which contain your compiled source code for your control.

What are we going to build today?
Today we'll be taking apart one of the components of Devhood. If you are in the top of most's our pages, and you'll notice a Yahoo! Style navigation bar that looks as this:



Home > Tutorials > General asp.net > Creating Custom Web Controls



This navigation bar is actually generated dynamically for each page by a Custom Web control. Let's start by looking at the the "the" code.


Namespace Mynavbar {
Using System;
Using System.Web.UI;
Using System.Web.UI.HtmlControls;
Using System.Web.UI.WebControls;
Using System.Collections;
Using System.Drawing;



We begin by giving my Web control a namespace and so we can reference it in the other pages. We ll also import all the namespaces we'll need for our Web control. On. aspx pages, the following namespaces are imported by default, but for Web Controls in. cs files, and you'll need to import them yourself if you ' ll need them:
System
System.Web
System.Web.UI
System.Web.UI.HtmlControls
System.Web.UI.WebControls
System.Collections
System.IO


public class Navbar:webcontrol {
private string strseperator = ">";
private int irpad = 3;
private int ilpad = 1;

public string Seperator {
get {return strseperator;}
set {strseperator = value;}
}

public int Lpad {
get {return ilpad;}
set {Ilpad = value;}
}

public int Rpad {
get {return irpad;}
set {Irpad = value;}
}



This section of the code defines the "class for" Web control, which is NavBar, and specifies it are a public class which can Be instantiated by any page. We also speciify that NavBar should derive to the Wwebcontrol class. Remember that since we imported then System.Web.UI.WebControls class we didn ' t need to-use the Full-qualified namespace re Ference to the WebControls class. I.e, we could just use WebControl instead the public class NavBar:System.Web.UI.WebControls.WebControl.

Next we define class variables that we'll use the building our navigation Bar. We'll want the developer to being able to specify properties of the control such as what would be used to separate the element s, and the spacing between the seperator. You'll be what ' ve defined class variables to hold these properties, mainly Strseperator, Ilpad, Irpad. However, in order to set this properties in a page, we define the getter/setter methods for them as above.

Now we can finally get to the heart of the code. The WebControl class contains a overrideable method CreateChildControls () which are called whenever the WebControl is init Ialized. This is the where all we control creation are done.


protected override void CreateChildControls () {

Build to the right Padding string.
string strrpad = String.Empty;
for (int i = 0; i < Irpad; i++) {
Strrpad + = "";
}

Build up the left Padding string.
string strlpad = String.Empty;
for (int i = 0; i < Ilpad; i++) {
Strlpad + = "";
}

Label Lblseparator;
Lblseparator = new Label ();
Lblseparator.text = Strlpad + Strseparator + strrpad;




Again we ' ll want to start out by performing some initialization steps. We'll build up a string containing the amount of white spaces as specified by the Rpad and Lpad properties. Remember, we defined the Getter/setter properties for this class variables, so they can is changed by the user. The default values for them are 3 and 1, since we initialized them to this values when we defined the variables above. We also create a Label control lblseparator which, as the name suggests, 'll be the separator between elements the Nav Igation Bar. This label consists to the left padding concatenated and the user specified Separator string (this is the string ">" By default), along with the right padding.


Iterate through the ArrayList of hyperlinks and place the seperators and padding
String in between the hyperlinks.
HyperLink HL;

HL = new HyperLink ();
hl. Text = "Home";
hl. NavigateUrl = "/";
Controls.Add (HL);



Here we begin by declaring then initializing a HyperLink object. The ' the ' of the ' navigation bar ' would always be pointing to ' home ' and it's navigateurl would always be '/' (The RO OT directory your Web site. Notice the Line Controls.Add (HL). This adds the created "home" HyperLink to the NavBar WebControl ' s ControlCollection Object. The ControlCollection Object provides a container for the NavBar to keep a list of it child controls.


Start the iteratation at I=1 because we want to disregard the
The array after the Split because it'll be a empty string. We Also
Want to disregard the "last element of the" array because that'll just be
The file name, which is replaced with the title of the page.
string[] Apath = Page.Request.Path.Split (new char[] {'/'});
int cntpath = Apath.length;
String strlinktext = "";
String strcompleteurl = "";
for (int i=1;i < Cntpath; i++) {
Controls.Add (Lblseperator);

HL = new HyperLink ();
Strlinktext = Apath[i]. ToString ();
hl. Text = Char.ToUpper (strlinktext[0]) + strlinktext.substring (1). ToLower ();

Strcompleteurl + = "/" +apath[i]. ToString ();
hl. NavigateUrl = Strcompleteurl;

Controls.Add (HL);
}
}
}
}



Notice here how we set the Apath string array. We do this by the getting of the Path from the Page ' s HttpRequest Object. Then we ' ll call C # ' s Split method on the Path string. We'll want to split by the '/' character and since our website URL are usually in the form http://www.devhood.com/subfolder1/s Ubfolder2/page.aspx.

Now so we have split the current page "s path into a string array, we can loop through this array to build up our Navigat Ion Bar.

At each iteration of the loop, and we add the Separator Label to the ControlCollection Object. Next we create a HyperLink Object consisting of the path name as the Text, and the complete URL for that path as the Navig Ateurl. Because this HyperLink Object is only links to a Path, or folder into your Web site, you'll need to make sure the correct Defau Lt page loads up automatically the pointing to a folder of your website. For example, Microsoft IIS looks for files such as Default.aspx and Default.htm as the "page to load" when a link points to A path or folder of a website rather than a file or page. The file names and search order can is custom configured in IIS.

When we are finished creating the HyperLink object we'll add it to the ControlCollection object as.

Because the "Add method" on the Controls object appends to the "end of" the ControlCollection object, we can be assured that O ur navigation Bar would appear in the correct order.

That ' s it!! We ' re done. Now all of that's left are to compile the code, where the DLL file into our Web application ' s bin directory and then we'll be Able to use this Web control on any of our pages by referencing it's namespace and class.

To ASP.net page, we'll need to add the following directive on the top of each page:


<%@ Register tagprefix= "mybar" namespace= "Mynavbar"%>





Then we can render the page with the following line:


<mybar:navbar rpad=5 lpad=2 separator= ">" Runat=server/>




I Hope this tutorial has helped your learn how to create custom controls in C #. Now you are able to go out and create your own navigation Bar, or "should" in C #. Remember This navigation Bar can easily is modified to show page titles instead the file names, or extended by adding prope rties to customize color, font, font-family, etc. This are left as a exercise to the reader, so go out and create a better more flexible navigation Bar for your site from The techniques ' ve learned here. If you are have any questions or comments, please post them below.




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.