Use Visual C #. Net to write server date controls

Source: Internet
Author: User
I. Preface

Visual C #. Net is a new product of Microsoft.Programming Language(Hereinafter referred to as C #), which inherits some features of the C language and adds some new elements. I used Delphi for development.ProgramWhen I first started using C #, I felt like a stranger (at least me ). Yes. The founder of C # Was the Anders hejlsberg who previously developed the Delphi language at Borland. When I started to use C # To develop a program, I thought it was a great rad tool for developing Windows form & web programs.
In terms of developing web programs, the emergence of C # Breaks the previous web development mode and implements and develops windows

The Form program has the same WYSIWYG functionality. C # provides some common web form Control for developers, and it is very simple to drag the control into the page. However, sometimes these controls cannot meet the needs of developers. developers need to write user control or custom control to meet their needs. Here, I will explain how to develop server controls in C.

2. Prerequisites

In C #, you can develop two types of server controls: User Control and custom control ). The nature of user controls is similar to that of page files (aspx files). It is HTML that can be reused by other aspx pages.CodeOf course, it also includes the code-behind and the suffix is ascx. Therefore, it is often used when developing public static pages (such as the page header and footer), but its disadvantage is that it is not easy to inherit and distribute, and it cannot be compiled into binary code for deployment. However, custom controls are much more powerful. They can be compiled into binary code (DLL files) and can be extended, inherited, and distributed. Like web form control, each of these controls is a DLL file.

It is relatively simple to Develop User Controls, just like writing An ASPX page, which is not described here. The object in this article is a custom control. The base class of the server control is system. Web. UI. Control. To develop visual server controls, we need to inherit from system. Web. UI. webcontrols; otherwise, we will inherit from system. Web. UI. Control.

The server control is designed with the runat = "server" script code embedded into the aspx file, indicating that the control runs on the server. The viewstate (view State) is used to maintain the status of the control during the submission and return (PostBack) Process on the page where the server control is located. Therefore, when designing server control properties, the value should be stored in viewstate.

Iii. Coding

C # There is a calendar control calendar, but now I need a calendar control that can be pulled down, and the calendar is not displayed at the beginning. It only pops up when I click the drop-down button, when a date is selected, the calendar is automatically hidden and the selected date value is displayed in the corresponding input box. Obviously, the calendar control cannot meet my needs, but I will use it later in my custom control.

Create a project, select Visual C # project in the project type, select the web control library in the template list, enter the project name aquacalendar, select the project directory, and click OK. C # generates the basic framework code. Rename the class file and class name in the project to datepicker (that is, the Class Name of the date control ). Since datepicker is a visual control, we must inherit from system. Web. UI. webcontrols. It includes an input box, a button, and a calendar control, which must be declared in the datepicker class. A composite control that combines multiple server controls. The Code is as follows. Important methods and codes are described in the annotations:

Using system;
Using system. Web. UI;
Using system. Web. UI. webcontrols;
Using system. componentmodel;
Using system. drawing;

Namespace aquacalendar
{
[Defaultproperty ("text"), // default attribute displayed in the property toolbox
Toolboxdata ("<{0}: datepicker runat = Server> </{0}: datepicker>")]
Public class datepicker: system. Web. UI. webcontrols. webcontrol, ipostbackeventhandler
{
// Select the default style of the date button
Private const string _ buttondefaultstyle = "border-Right: Gray 1px solid; border-top: Gray 1px solid; border-left: Gray 1px solid; cursor: hand; border-bottom: gray 1px solid ;";

// Button default text

Private const string _ buttondefaulttext = "...";
Private system. Web. UI. webcontrols. Calendar _ calendar;

Public override controlcollection controls
{
Get
{
Ensurechildcontrols (); // confirm that the child control set has been created
Return base. controls;
}
}

// Create a child control (server calendar Control)

Protected override void createchildcontrols ()
{
Controls. Clear ();
_ Calendar = New Calendar ();
_ Calendar. ID = mycalendarid;
_ Calendar. selecteddate = datetime. parse (text );
_ Calendar. titleformat = titleformat. monthYear;
_ Calendar. nextprevformat = nextprevformat. interval month;
_ Calendar. cellspacing = 0;
_ Calendar. Font. size = fontunit. parse ("9pt ");
_ Calendar. Font. Name = "verdana ";
_ Calendar. selecteddaystyle. backcolor = colortranslator. fromhtml ("#333399 ");
_ Calendar. selecteddaystyle. forecolor = colortranslator. fromhtml ("white ");
_ Calendar. daystyle. backcolor = colortranslator. fromhtml ("# cccccc ");
_ Calendar. todaydaystyle. backcolor = colortranslator. fromhtml ("#999999 ");
_ Calendar. todaydaystyle. forecolor = colortranslator. fromhtml ("Aqua ");
_ Calendar. dayheaderstyle. Font. size = fontunit. parse ("8pt ");
_ Calendar. dayheaderstyle. Font. Bold = true;
_ Calendar. dayheaderstyle. Height = unit. parse ("8pt ");
_ Calendar. dayheaderstyle. forecolor = colortranslator. fromhtml ("#333333 ");
_ Calendar. nextprevstyle. Font. size = fontunit. parse ("8pt ");
_ Calendar. nextprevstyle. Font. Bold = true;
_ Calendar. nextprevstyle. forecolor = colortranslator. fromhtml ("white ");
_ Calendar. titlestyle. Font. size = fontunit. parse ("12pt ");
_ Calendar. titlestyle. Font. Bold = true;
_ Calendar. titlestyle. Height = unit. parse ("12pt ");
_ Calendar. titlestyle. forecolor = colortranslator. fromhtml ("white ");
_ Calendar. titlestyle. backcolor = colortranslator. fromhtml ("#333399 ");
_ Calendar. othermonthdaystyle. forecolor = colortranslator. fromhtml ("#999999 ");
_ Calendar. nextprevformat = nextprevformat. customtext;
_ Calendar. nextmonthtext = "Next Month ";
_ Calendar. prevmonthtext = "last month ";
_ Calendar. style. Add ("display", "NONE"); // The drop-down calendar control is not displayed by default.
_ Calendar. selectionchanged + = new eventhandler (_ calendar_selectionchanged );
This. Controls. Add (_ calendar );
}
[
Category ("appearance"), // category of this attribute, see Figure
Defaultvalue (""), // default Attribute Value
Description ("sets the date control value. ") // Attribute description
]

Public String text
{
Get
{
Ensurechildcontrols ();
Return (viewstate ["text"] = NULL )? System. datetime. Today. tostring ("yyyy-mm-dd"): viewstate ["text"]. tostring ();
}
Set
{
Ensurechildcontrols ();
Datetime dt = system. datetime. today;
Try
{
Dt = datetime. parse (value );
}
Catch
{
Throw new argumentoutofrangeexception ("enter a date string (for example, 1981-04-29 )! ");
}

Viewstate ["text"] = dateformat = calendarenum. longdatetime? DT. tostring ("yyyy-mm-dd"): DT. tostring ("yyyy-m-d ");
}
}

// Reload the enabled attribute of the server control to disable the date selection button)

Public override bool Enabled
{
Get
{
Ensurechildcontrols ();
Return viewstate ["enabled"] = NULL? True: (bool) viewstate ["enabled"];
}
Set
{
Ensurechildcontrols ();
Viewstate ["enabled"] = value;
}
}

Public String buttonstyle
{
Get
{
Ensurechildcontrols ();
Object o = viewstate ["buttonsytle"];
Return (O = NULL )? _ Buttondefaultstyle: O. tostring ();
}
Set
{
Ensurechildcontrols ();
Viewstate ["buttonsytle"] = value;
}
}

[
Defaultvalue (calendarenum. longdatetime ),
]

Public calendarenum dateformat
{
Get
{
Ensurechildcontrols ();
Object format = viewstate ["dateformat"];
Return format = NULL? Calendarenum. longdatetime :( calendarenum) format;
}
Set
{
Ensurechildcontrols ();
Viewstate ["dateformat"] = value;
Datetime dt = datetime. parse (text );
TEXT = dateformat = calendarenum. longdatetime? DT. tostring ("yyyy-mm-dd"): DT. tostring ("yyyy-m-d ");
}
}

[
Browsable (false ),
Designerserializationvisibility (designerserializationvisibility. Hidden)
]

Public String mycalendarid // Compound Control ID
{
Get
{
Ensurechildcontrols ();
Return this. clientid + "_ mycalendar ";
}
}

[
Browsable (false ),
Designerserializationvisibility (designerserializationvisibility. Hidden)
]

Public String mycalendarname // Composite Control name
{
Get
{
Ensurechildcontrols ();
Return this. uniqueid + ": mycalendar ";
}
}

[
Browsable (false ),
Designerserializationvisibility (designerserializationvisibility. Hidden)
]

Public String datepickerinputid // ID of the input box in the Composite Control
{
Get
{
Ensurechildcontrols ();
Return this. clientid + "_ dateinput ";
}
}

[
Browsable (false ),
Designerserializationvisibility (designerserializationvisibility. Hidden)
]

Public String datepickerinputname // name of the input box in the Composite Control
{
Get
{
Ensurechildcontrols ();
Return this. uniqueid + ": dateinput ";
}
}

[
Browsable (false ),
Designerserializationvisibility (designerserializationvisibility. Hidden)
]

Public String datepickerbuttonid // the ID of the button in the Composite Control
{
Get
{
Ensurechildcontrols ();
Return this. clientid + "_ datebutton ";
}
}

[
Browsable (false ),
Designerserializationvisibility (designerserializationvisibility. Hidden)
]

Public String datepickerbuttonname // name of the button in the Composite Control
{
Get
{
Ensurechildcontrols ();
Return this. uniqueid + ": datebutton ";
}
}

Public String buttontext
{
Get
{
Ensurechildcontrols ();
Return viewstate ["buttontext"] = NULL? _ Buttondefatext text :( string) viewstate ["buttontext"];
}
Set
{
Ensurechildcontrols ();
Viewstate ["buttontext"] = value;
}
}

/// <Summary>
/// Present the control to the specified output parameter.
/// </Summary>
/// <Param name = "output"> HTML writer to be written </param>

Protected override void render (htmltextwriter output)
{
// When the control is output on the page, a table (two rows and two columns) is generated. The following is the table style.
Output. addattriing (htmltextwriterattribute. cellspacing, "0 ");
Output. addattribute (htmltextwriterattribute. Border, "0 ");
Output. addattriding (htmltextwriterattribute. cellpadding, "0 ");

Output. addstyleattribute ("Left", this. Style ["Left"]);
Output. addstyleattribute ("TOP", this. Style ["TOP"]);
Output. addstyleattribute ("position", "absolute ");

If (width! = Unit. Empty)
{
Output. addstyleattribute (htmltextwriterstyle. Width, width. tostring ());
}
Else
{
Output. addstyleattribute (htmltextwriterstyle. Width, "200px ");
}

Output. renderbegintag (htmltextwritertag. Table); // output table
Output. renderbegintag (htmltextwritertag. tr); // the first row of the table
Output. addattribute (htmltextwriterattribute. Width, "90% ");
Output. renderbegintag (htmltextwritertag. TD );

// The attributes and style settings of the text box in the first column of the First row are as follows:

If (! Enabled)
{
Output. addattribute (htmltextwriterattribute. readonly, "true ");
}

Output. addattribute (htmltextwriterattribute. type, "text ");
Output. addattrid (htmltextwriterattribute. ID, datepickerinputid );
Output. addattribute (htmltextwriterattribute. Name, datepickerinputname );
Output. addattriter( htmltextwriterattribute. Value, text );
Output. addstyleattribute (htmltextwriterstyle. Width, "100% ");
Output. addstyleattribute (htmltextwriterstyle. Height, "100% ");
Output. addstyleattribute (htmltextwriterstyle. fontfamily, Font. Name );
Output. addstyleattribute (htmltextwriterstyle. fontsize, Font. Size. tostring ());
Output. addstyleattribute (htmltextwriterstyle. fontweight, Font. Bold? "Bold ":"");
Output. addstyleattribute (htmltextwriterstyle. backgroundcolor, colortranslator. tohtml (backcolor ));
Output. addstyleattribute (htmltextwriterstyle. Color, colortranslator. tohtml (forecolor ));
Output. renderbegintag (htmltextwritertag. Input); // output text box
Output. renderendtag ();
Output. renderendtag ();
Output. addattribute (htmltextwriterattribute. Width ,"*");
Output. renderbegintag (htmltextwritertag. TD );

// The following are the button attributes and style settings in the second column of the first row.

If (! Enabled)
{
Output. addattribute (htmltextwriterattribute. Disabled, "true ");
}

Output. addattrimit (htmltextwriterattribute. type, "Submit ");
Output. addattribute (htmltextwriterattribute. ID, datepickerbuttonid );
Output. addattribute (htmltextwriterattribute. Name, datepickerbuttonname );
Output. addattribute (htmltextwriterattribute. Value, buttontext );
Output. addstyleattribute (htmltextwriterstyle. Width, "100% ");
Output. addattribute (htmltextwriterattribute. onclick, page. getpostbackeventreference (this); // when you click the button, you need to return it to the server to trigger the next onclick event.

Output. addattribute (htmltextwriterattribute. style, buttonstyle );
Output. renderbegintag (htmltextwritertag. Input); // output button
Output. renderendtag ();
Output. renderendtag ();

Output. renderendtag ();
Output. renderbegintag (htmltextwritertag. tr );
Output. addattribute (htmltextwriterattribute. colspan, "2 ");
Output. renderbegintag (htmltextwritertag. TD );
_ Calendar. rendercontrol (output); // outputs the calendar subcontrol.
Output. renderendtag ();
Output. renderendtag ();
Output. renderendtag ();
}

// The Composite Control must inherit the ipostbackeventhandler interface to inherit the raisepostbackevent

Public void raisepostbackevent (string eventargument)
{
Onclick (eventargs. Empty );
}

Protected virtual void onclick (eventargs E)
{
// When you click the select date button, if the calendar subcontrol is not displayed, it is displayed and the value of the text box is assigned to the calendar subcontrol.
If (_ calendar. attributes ["display"]! = "")
{
_ Calendar. selecteddate = datetime. parse (text );
_ Calendar. style. Add ("display ","");
}
}

// Date change event of the calendar control in the Composite Control

Private void _ calendar_selectionchanged (Object sender, eventargs E)
{
// When the selected date changes, assign the selected date to the text box and hide the calendar subcontrol
TEXT = _ calendar. selecteddate. tostring ();
_ Calendar. style. Add ("display", "NONE ");
}
}
}

In the above Code, pay attention to the following points:

· If you want to overload some attributes of the control, add the virtual keyword before declaring the attribute;

· When the control is output on the page (that is, in the render event), the style or attribute of the subcontrol is defined first, and then the subcontrol is generated;

· When hiding the calendar sub-control, we recommend that you do not use the visible attribute to display/hide the calendar sub-control. If you use visible = false to hide the sub-control, the server will not send the HTML code of the calendar control to the client, the composite control loads a blank table of the calendar control, affecting the page layout. Therefore, the style display = none is used to hide the calendar control on the client, but the HTML code still exists on the page;

Iv. Conclusion

When writing server controls, you must understand the request processing method of the. NET program based on the HTML language. The server control encapsulates client behavior and logic judgment without the need for developers to add more code. Of course, using server controls in some places can bring convenience, but also increase the load on the server. Sometimes it is appropriate to combine JavaScript to run some code on the client, which can improve the efficiency of Web applications.

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.