欢迎光临
我们一直在努力

Creating Custom Web Controls in C# Stats(转)-.NET教程,C#语言

建站超值云服务器,限时71元/月

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 now you may or may not have heard of asp.nets web controls. in this tutorial i plan to discuss the advantages of using web controls, as well as how to create and deploy them in c#.

what are web controls?

web controls are widgets that can be reused across multiple webpages. controls may render html to the client, or other formats such as wml or xml. if youre familiar with asp.net, youll know that asp.net provides some controls for you 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 you the hassle of writing similar html on multiple pages by generating the appropriate html for you.

but why use c#? cant we just use .ascx files?
.ascx files are another way of creating reusable controls. however, it doesnt always provide a clean way of separating your code from content. what this means is that content developers can write content, graphic artists and ui experts can layout your site, and you can develop the logic behind everything without overlapping each other. in addition, when deploying your web site or giving your web site to someone else, by using controls written in c# and pre-compiled, you wont have to give them any of your source code to launch your site, all you need to give them are the dlls which contain your compiled source code for your control.

what are we going to build today?
today well be taking apart one of the components of devhood. if you look at the top of most of our pages, youll notice a yahoo! style navigation bar that looks something like 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. lets start by looking at the first part of 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 our web control a namespace, so that we can reference it in other pages. well also import all the namespaces well need for our web control. on .aspx pages, the following namespaces are imported by default, but for web controls in .cs files, youll need to import them yourself if youll 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 code defines the class for the web control, which is navbar, and specifies it is a public class which can be instantiated by any page. we also speciify that navbar should derive from the wwebcontrol class. remember that since we imported then system.web.ui.webcontrols class we didnt need to use the full-qualified namespace reference to the webcontrols class. i.e, we could just use webcontrol instead of public class navbar : system.web.ui.webcontrols.webcontrol.

next we define class variables that well use in building our navigation bar. well want the developer to be able to specify properties of the control such as what will be used to separate the elements, and the spacing between the seperator. youll see whatve defined class variables to hold these properties, mainly strseperator, ilpad, irpad. however, in order to set these 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 an overrideable method createchildcontrols() which is called whenever the webcontrol is initialized. this is where all of our control creation will be done.

protected override void createchildcontrols() {
            
    //build up 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 well want to start out by performing some initialization steps. first well 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 these class variables, so they can be changed by the user. the default values for them are 3 and 1, since we initialized them to these values when we defined the variables above. we also create a label control lblseparator which, as the name suggests, will be the separator between elements of the navigation bar. this label consists of the left padding, concatenated with 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 first element of the navigation bar will always be pointing to "home", and its navigateurl will always be "/" (the root directory of your web site). notice the line controls.add(hl). this adds the created "home" hyperlink to the navbar webcontrols controlcollection object. the controlcollection object provides a container for the navbar to keep a list of its child controls.

    //start the iteratation at i=1 because we want to disregard the first element
    //of the array after the split because it will be an empty string. we also
    //want to disregard the last element of the array because that will just be
    //the file name, which will be 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 first getting the path from the pages httprequest object. then well call c#s split method on the path string. well want to split by the / character, since our website url is usually in the form http://www.devhood.com/subfolder1/subfolder2/page.aspx.

now that we have split the current pages path into a string array, we can loop through this array to build up our navigation bar.

at each iteration of the loop, 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 navigateurl. because this hyperlink object only links to a path, or folder in your web site, youll need to make sure the correct default page loads up automatically when 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 be custom configured in iis.

when we are finished creating the hyperlink object well add it to the controlcollection object as well.

because the add method on the controls object appends to the end of the controlcollection object, we can be assured that our navigation bar will appear in the correct order.

thats it!! were done. now all thats left is to compile the code, place the dll file into our web applications bin directory and then well be able to use this web control on any of our pages by referencing its namespace and class.

to use this control in an asp.net page, well need to add the following directive at the top of each page:

  <%@ register tagprefix="mybar" namespace="mynavbar" %>

then we can render this control on the page with the following line:

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

i hope this tutorial has helped you learn how to create custom controls in c#. now you should be able to go out and create your own navigation bar, or other custom control in c#. remember this navigation bar can easily be modified to show page titles instead of file names, or extended by adding properties to customize color, font, font-family, etc. this is left as an exercise for the reader, so go out and create a better more flexible navigation bar for your site from the techniques youve learned here. if you have any questions or comments, please post them below.

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » Creating Custom Web Controls in C# Stats(转)-.NET教程,C#语言
分享到: 更多 (0)