首页 > 开发 > 综合 > 正文

Creating Custom Web Controls in C# Stats(转)

2024-07-21 02:20:18
字体:
来源:转载
供稿:网友
creating custom web controls in c#    stats  
  rating: 4.75 out of 5 by 4 users  
  submitted: 04/09/01  


peter weng ([email protected])  


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

  
by now you may or may not have heard of asp.net's 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 you're familiar with asp.net, you'll 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#? 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 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 won't have to give them any of your source code to launch your site, all you need to give them are 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 look at the top of most of our pages, you'll 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. let's 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. 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, 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 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 didn't 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 we'll use in building our navigation bar. we'll 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. you'll see what've 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 we'll want to start out by performing some initialization steps. first 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 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 it's 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 webcontrol's 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 page's httprequest object. then we'll call c#'s split method on the path string. we'll 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 page's 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, you'll 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 we'll 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.

that's it!! we're done. now all that's left is to compile the code, place 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 use this control in an asp.net page, we'll 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 you've learned here. if you have any questions or comments, please post them below.


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表