Original control code sharing-date Selection Control

Source: Internet
Author: User
Tags dateformat

Idea: Select date, year, month, and day
1. You can set the start and end years of a year.
2. exclude the possibility of incorrect date Selection
3. control using JavaScript
4. Use the text attribute to conveniently obtain the set date value

Welcome to: http: // 121.18.78.216, which is a demonstration platform for ease of query and analysis, workflow, content management, and project management.
======================================
The Code is as follows:
Using system;
Using system. collections;
Using system. Collections. Specialized;
Using system. componentmodel;
Using system. IO;
Using system. text;
Using system. Web. UI;
Using system. Web. UI. Design. webcontrols;
Using system. Web. UI. webcontrols;

Namespace jsy
{
/// <Summary>
/// Aspnetdate select the input date Control
/// </Summary>
[Defaultproperty ("text "),
Parsechildren (false ),
Persistchildren (false ),
Description ("date control dedicated to ASP. NET web applications "),
Designer (typeof (datedesigner )),
Toolboxdata ("<{0}: jsynetdate runat = Server> </{0}: jsynetdate>")]
Public class jsynetdate: panel, inamingcontainer, ipostbackdatahandler
{
# Region attributes
/// <Summary>
/// Obtain/set the date value.
/// </Summary>
[Bindable (true ),
Browsable (true ),
Description ("date value "),
Category ("appearance "),
Defaultvalue ("")]
Public String text
{
Get
{
If (viewstate ["text"]! = NULL)
{
Return viewstate ["text"]. tostring ();
}
Else
{
If (isnull)
{
Return "";
}
Else
{
Datetime date = system. datetime. today;
String STR = "";
Switch (dateformat)
{
Case "ymd ":
STR = date. tostring ("yyyy-mm-dd", system. Globalization. datetimeformatinfo. invariantinfo );
Break;
Case "ym ":
STR = date. tostring ("yyyy-mm", system. Globalization. datetimeformatinfo. invariantinfo );
Break;
Case "Y ":
STR = date. year. tostring ();
Break;
}
Return STR;
}
}
}

Set
{
If (value = "")
{
Viewstate ["text"] = "";
}
Else if (dateformat = "ymd ")
{
Datetime date;
Try
{
Date = convert. todatetime (value );
}
Catch
{
Date = system. datetime. today;
}
String STR = date. tostring ("yyyy-mm-dd", system. Globalization. datetimeformatinfo. invariantinfo );
If (STR = "1900-01-01 ")
STR = "";
Viewstate ["text"] = STR;
}
Else
{
Viewstate ["text"] = value;
}
}
}
/// <Summary>
/// Obtain/set whether the date value is allowed to be null.
/// </Summary>
[Browsable (true ),
Description ("whether the date value can be blank "),
Category ("layout "),
Defaultvalue (false)]
Public bool isnull
{
Get
{
Return (viewstate ["isnull"] = NULL )? False: true;
}
Set
{
If (value)
Viewstate ["isnull"] = true;
}
}
/// <Summary>
/// Obtain/set the date value format (ymd: year-month-day ym: year-month Y: year ).
/// </Summary>
[Browsable (true ),
Description ("date value format (ymd: year-month-day ym: year-month Y: Year )"),
Category ("layout "),
Defaultvalue ("ymd")]
Public String dateformat
{
Get
{
Return (viewstate ["dateformat"] = NULL )? "Ymd" :( string) viewstate ["dateformat"];
}

Set
{
Viewstate ["dateformat"] = value;
}
}
/// <Summary>
/// Obtain/set whether the date value can be edited.
/// </Summary>
[Browsable (true ),
Description ("editable "),
Category ("behavior "),
Defaultvalue (true)]
Public override bool Enabled
{
Get
{
Return (viewstate ["enabled"] = NULL )? True: false;
}

Set
{
If (! Value)
Viewstate ["enabled"] = false;
}
}
/// <Summary>
/// Obtain/set the length of the year that can be selected in the date value.
/// </Summary>
[Browsable (true ),
Description ("the length of the year that can be selected in the date value "),
Category ("layout "),
Defaultvalue (100)]
Public int Length
{
Get
{
Object OBJ = viewstate ["length"];
Return (OBJ = NULL )? 100 :( INT) OBJ;
}

Set
{
Viewstate ["length"] = value;
}
}
/// <Summary>
/// Obtain/set the end value of the selected year.
/// </Summary>
[Browsable (true ),
Description ("select the end year in the date value. If it is less than 100, it indicates the number of years earlier "),
Category ("layout "),
Defaultvalue (0)]
Public int end
{
Get
{
Object OBJ = viewstate ["end"];
Int y;
If (OBJ = NULL)
{
Y = system. datetime. Today. Year;
}
Else
{
Y = (INT) OBJ;
If (Y <1, 100)
{
Y = system. datetime. Today. Year + Y;
}
}
Return y;
}

Set
{
Viewstate ["end"] = value;
}
}
/// <Summary>
/// Obtain the start value of the selected year.
/// </Summary>
[Browsable (false ),
Designerserializationvisibility (designerserializationvisibility. Hidden)]
Public int start
{
Get {return end-length ;}
}

# Endregion
# Region rewrite event
/// <Summary>
/// Rewrite the onload method.
/// </Summary>
/// <Param name = "E"> <see CREF = "eventargs"/> object that contains event data. </Param>
Protected override void onload (eventargs E)
{
If (page. ispostback)
{
String y = page. Request. Form [This. uniqueid + "_ year"];
String M = page. Request. Form [This. uniqueid + "_ month"];
String d = page. Request. Form [This. uniqueid + "_ day"];
Switch (dateformat)
{
Case "ymd ":
If (y = "" | M = "" | D = "")
{
TEXT = "";
}
Else
{
TEXT = Y + "-" + M + "-" + D;
}
Break;
Case "ym ":
If (y = "" | M = "")
{
TEXT = "";
}
Else
{
TEXT = Y + "-" + m;
}
Break;
Case "Y ":
If (y = "")
{
TEXT = "";
}
Else
{
TEXT = y;
}
Break;
}
}
Base. onload (E );
}
/// <Summary>
/// Override the <see CREF = "system. Web. UI. webcontrols. webcontrol. addattributestorender"/> method to verify whether the form (runat = server) control exists.
/// </Summary>
/// <Param name = "Writer"> </param>
Protected override void addattributestorender (htmltextwriter writer)
{
If (this. Page! = NULL)
This. Page. verifyrenderinginserverform (this );
Base. addattributestorender (writer );
}
/// <Summary>
/// Override the <see CREF = "system. Web. UI. Control. onprerender"/> method.
/// </Summary>
/// <Param name = "E"> <see CREF = "eventargs"/> object that contains event data. </Param>
Protected override void onprerender (eventargs E)
{
String <a href = "mailto: strjs = @" <script "> strjs = @" <script language = 'javascript '>

// Original: Jia Shiyi Date: free sharing V1.0
// Mail: jsyhello76@126.com
// Please respect copyright and use it at will, but please indicate the source //

Function inityear (pname, start, length, Y)
{
VaR selyear = eval ('document. Forms [0]. '+ pname +' _ year ');
VaR n = selyear. length;
Selyear. Length = N + Length + 1;
For (I = 0; I <= length; I ++)
{
Selyear. Options [n + I]. value = (I + start );
Selyear. Options [n + I]. Text = (I + start );
}
If (y = 0)
{
Selyear. selectedindex = 0;
}
Else
{
If (Y> start)
{
If (Y-start <= length)
{
Selyear. selectedindex = N + Y-start;
}
Else
{
Selyear. selectedindex = length;
}
}
}
}

Function initmonth (pname, m)
{
VaR selmonth = eval ('document. all. '+ pname +' _ month ');
VaR n = selmonth. length;
Selmonth. Length = N + 12;
For (I = 1; I <10; I ++)
{
Selmonth. Options [n + I-1]. value = '0' + I;
Selmonth. Options [n + I-1]. Text = I;
}
For (I = 10; I <= 12; I ++)
{
Selmonth. Options [n + I-1]. value = I;
Selmonth. Options [n + I-1]. Text = I;
}
If (M = 0)
{
Selmonth. selectedindex = 0;
}
Else
{
Selmonth. selectedindex = N + m-1;
}
}

Function initday (pname, d)
{
VaR selday = eval ('document. all. '+ pname +' _ Day ');
VaR n = selday. length;
Selday. Length = N + 31;
For (I = 1; I <10; I ++)
{
Selday. Options [n + I-1]. value = '0' + I;
Selday. Options [n + I-1]. Text = I;
}
For (I = 10; I <= 31; I ++)
{
Selday. Options [n + I-1]. value = I;
Selday. Options [n + I-1]. Text = I;
}
If (D = 0)
{
Selday. selectedindex = 0;
}
Else
{
Selday. selectedindex = N + D-1;
}
Datechange (pname );
}

Function datechange (pname)
{
VaR selyear = eval ('document. Forms [0]. '+ pname +' _ year ');
VaR year = selyear. Options [selyear. selectedindex]. value;
If (year! = '')
{
VaR selmonth = eval ('document. all. '+ pname +' _ month ');
VaR month = selmonth. Options [selmonth. selectedindex]. value;
If (month! = '')
{
VaR date = new date (year, month, 0 );
VaR day = date. getdate ();
VaR selday = eval ('document. all. '+ pname +' _ Day ');
VaR TMP = 1;
If (selday. selectedindex> 0)
{
TMP = selday. Options [selday. selectedindex]. value;
}
Selday. Length = Day;
For (I = 1; I <10; I ++)
{
Selday. Options [I-1]. value = '0' + I;
Selday. Options [I-1]. Text = I;
}
For (I = 10; I <= day; I ++)
{
Selday. Options [I-1]. value = I;
Selday. Options [I-1]. Text = I;
}
If (TMP> Day)
{
Selday. selectedindex = day-1;
}
Else
{
Selday. selectedindex = tmp-1;
}
}
}
}

</SCRIPT> ";
Page. registerclientscriptblock ("enabledays", strjs );
Base. onprerender (E );
}
/// <Summary>
/// Present the control to the specified output parameter.
/// </Summary>
/// <Param name = "Writer"> HTML writer to be written </param>
Protected override void render (htmltextwriter writer)
{
Writer. Write ("<Table border = '0' cellpadding = '0' cellspacing = '0'> <tr> <TD nowrap align = 'left'> ");
Int y = 0;
Int m = 0;
Int D = 0;
String STR = text;
If (Str. length> = 4)
{
Y = convert. toint32 (Str. substring (0, 4 ));
If (Str. length> = 7)
{
M = convert. toint32 (Str. substring (5, 2 ));
If (Str. length> = 10)
{
D = convert. toint32 (Str. substring (8, 2 ));
}
}
}
Bool isdate = (dateformat = "ymd ");
If (Enabled)
{
Bool isnull = isnull;
Writer. Write ("<select name = '" + this. uniqueid + "_ year '");
If (isdate)
{
Writer. Write ("onchange =/" datechange ('"+ this. uniqueid + "')/"");
}
Writer. Write ("> ");
If (isnull)
{
Writer. Write ("<option value =''> </option> ");
}
Writer. Write ("</SELECT> year ");
If (dateformat. length> 1)
{
Writer. Write ("<select name = '" + this. uniqueid + "_ month '");
If (isdate)
{
Writer. Write ("onchange =/" datechange ('"+ this. uniqueid + "')/"");
}
Writer. Write ("> ");
If (isnull)
{
Writer. Write ("<option value =''> </option> ");
}
Writer. Write ("</SELECT> month ");
Writer. Write (@"
<Script language = 'javascript '>
Inityear ('"+ this. uniqueid + "'," + start. tostring () + "," + length. tostring () + "," + Y. tostring () + @");
Initmonth ('"+ this. uniqueid +"', "+ M. tostring () + @");
</SCRIPT> ");
If (isdate)
{
Writer. Write ("<select name = '" + this. uniqueid + "_ Day'> ");
If (isnull)
{
Writer. Write ("<option value =''> </option> ");
}
Writer. Write ("</SELECT> day ");
Writer. Write (@"
<Script language = 'javascript '>
Initday ('"+ this. uniqueid +"', "+ D. tostring () + @");
</SCRIPT> ");
}
}
}
Else
{
If (y = 0 | M = 0)
{
Writer. Write ("& nbsp ;");
}
Else
{
Writer. Write (Y. tostring () + "year" + M. tostring () + "month ");
If (D! = 0)
{
Writer. Write (D. tostring () + "day ");
}
}
}
Writer. Write ("</TD> </tr> </table> ");
}

Public event eventhandler textchanged;

/// <Summary>
/// When implemented by a class, it processes the send-back data for the ASP. NET Server Control.
/// </Summary>
/// <Param name = "postdatakey"> Primary identifier of the Control </param>
/// <Param name = "postcollection"> set of all input name values </param>
/// <Returns> If the status of the server control changes after sending back, the value is true; otherwise, the value is false. </Returns>
Public Virtual bool loadpostdata (string postdatakey, namevaluecollection postcollection)

{
String presentvalue = text;
String postedvalue = postcollection [postdatakey];

If (presentvalue = NULL |! Presentvalue. Equals (postedvalue ))
{
TEXT = postedvalue;
Return true;
}

Return false;
}


/// <Summary>
/// When implemented by a class, a signal is sent to the server control object to notify the ASP. NET application that the control status has changed.
/// </Summary>
Public Virtual void raisepostdatachangedevent ()
{
Ontextchanged (eventargs. Empty );
}

Protected virtual void ontextchanged (eventargs E)
{
If (textchanged! = NULL)
Textchanged (this, e );
}
# Endregion

}

# Region control designer
/// <Summary>
/// Server Control designer.
/// </Summary>
Public class datedesigner: system. Web. UI. Design. webcontrols. paneldesigner
{
/// <Summary>
/// Initialize a new pagerdesigner instance.
/// </Summary>
Public datedesigner ()
{
This. readonly = true;
}
Private jsynetdate WB;

/// <Summary>
/// Obtain the HTML used to represent the associated control during design.
/// </Summary>
/// <Returns> indicates the HTML of the control during design. </Returns>
Public override string getdesigntimehtml ()
{

WB = (jsynetdate) component;
WB. Text = "";
Stringwriter Sw = new stringwriter ();
Htmltextwriter writer = new htmltextwriter (SW );
WB. rendercontrol (writer );
Return Sw. tostring ();
}

/// <Summary>
/// Obtain the HTML that is displayed for the specified exception at design after an error is encountered when rendering the control.
/// </Summary>
/// <Param name = "E"> the exception for which you want to display the error message. </Param>
/// <Returns> the HTML that is displayed for the specified exception at design time. </Returns>
Protected override string geterrordesigntimehtml (exception E)
{
String errorstr = "An error occurred while creating the control:" + E. message;
Return createplaceholderdesigntimehtml (errorstr );
}
}
# Endregion
}
========================================
Save the preceding code as a file, such as jsynetdate. CS.
Use CSC/T: Library/out: ../bin/jsy. dll/R: system. Web. dll/R: system. dll jsynetdate. CS to compile the SDK.
==========================================
Please leave more valuable comments and I will continue to work hard
Example
<% @ Register tagprefix = "PC3" namespace = "jsy" assembly = "jsy" %>
<% @ Page Language = "C #" %>
<! 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">
<Div align = "center"> <br/>
<PC3: jsynetdate id = "jsynetdate1" length = "50" isnull = "true" runat = "server"> </PC3: jsynetdate>
<Br/>
<Asp: button id = "button1" runat = "server" text = "button"> </ASP: button>
</Div>
</Form>
</Body>
</Html>

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.