Create an ASP. NET web custom control)

Source: Internet
Author: User

Create an ASP. NET web custom control -- routine 1
Web custom control programming is a difficult part of ASP. NET programming. In particular, complicated controls require some technical skills that are not commonly used.
Based on some of my practical experience, I will introduce this technology to readers.
Simple inheritance control: confirmbutton
We are writing applications using ASP. NET.ProgramWhen the button is submitted, a [OK] [cancel] confirmation box is usually displayed to prevent users from submitting it by mistake. The traditional method to implement this function isCodeAdd the attributes of the button in the page_load event of the page, but it is troublesome to add each button. Next we will create a button with such a function to solve this problem.

(The routine uses the C # language)

1. Create a project

First Open visual studio.net and create a new web control library project named testlib. In Solution Explorer, there will be a webcustomcontrol1.csSource codeFile, and rename it confirmbutton. CS.

2. Edit the code

Open confirmbutton. cs source file, change the class name "webcustomcontrol1" to "confirmbutton", and inherit the class from "system. web. UI. webcontrols. change "webcontrol" to "system. web. UI. webcontrols. button ";

Run the code "[defaultproperty (" text "),

Toolboxdata ("<{0}: webcustomcontrol1 runat = server ></ {0}: webcustomcontrol1>")]"

Change to "[defaultproperty (" text "),

Toolboxdata ("<{0}: confirmbutton runat = Server> </{0}: confirmbutton>")] ", in this way, the XML Code ID of the control displayed on the ASPX page is displayed as "<cc0: confirmbutton…> ... </PC3: confirmbutton> ".

The following code is further modified to delete the original code:

Private string text;

[Bindable (true ),

Category ("appearance "),

Defaultvalue ("")]

Public String text

{

Get

{

Return text;

}

Set

{

TEXT = value;

}

}

Add new Code (used to set the information displayed in the pop-up confirmation box ):

Private string _ confirmmessage = "is OK? ";

[Bindable (true ),

Category ("appearance "),

Defaultvalue ("is OK? ")]

Public String confirmmessage

{

Get

{

Return _ confirmmessage;

}

Set

{

_ Confirmmessage = value;

}

}

Finally

Protected override void render (htmltextwriter output)

{

Output. Write (text );

}

Change to protected override void render (htmltextwriter output)

{

Base. Attributes. Add ("onclick", "Return confirm ('" + this. _ confirmmessage + "');");

Base. Render (output );

}

3. Add the icon displayed in the toolbox

Select the menu [project]/[add new item], select create "bitmap file" in the pop-up dialog box, and change the file name to "confirmbutton" (very important, the bitmap file name must be the same as the class name ). Select the bitmap file in solution Resource Manager and set the value of "generate operation" to "embedded resource" in the Property setting box ".

 

Okay. compile it. Everything is okay. The rest is to find the compiled DLL file and add it to the toolbox, which can be used in future Web applications.

Create an ASP. NET web custom control-routine 2

This article describes how to create a composite custom control through a complete piece of code, including custom attributes, event processing, and data transfer between controls.

The author has some controls and code in http://damao.0538.org, and in the update, interested readers can download.

The following is the code of a login box, including username input Textbox, password input Textbox, submit button, reset button, and panel that hosts the above four items. The control class is named loginctrl.

(Routine uses C #)

Using system;

Using system. Web. UI;

Using system. Web. UI. webcontrols;

Using system. componentmodel;

Using system. drawing;

 

Namespace testlib

{

[Defaultproperty ("backcolor "),

Toolboxdata ("<{0}: loginctrl runat = Server> </{0}: loginctrl>")]

Public class loginctrl: system. Web. UI. webcontrols. webcontrol

{

Private color _ fontcolor = color. Black; // declare the font color variable

Private color _ backcolor = color. White; // declare the control background variable

First, declare the child control to be used in the composite control.

Private Label lblusername = new label (); // display the "user name" label Control

Private Label lblpassword = new label (); // display the "password" label Control

Private textbox txtusername = new Textbox (); // Textbox Control for user name input

Private textbox txtpassword = new Textbox (); // Textbox Control for Password Input

Private button submitbutton = new button (); // submit the button control

Private button clearbutton = new button (); // reset the button control

Private system. Web. UI. webcontrols. Panel pnlframe = new system. Web. UI. webcontrols. Panel (); // container panel control that carries other controls

Of course, you must declare the events used in the compliance control. They will appear in the event bar of the attribute box.

Public event eventhandler submitonclick; // declare the submit event of the custom control loginctrl

Public event eventhandler clearonclick; // declare the reset event of the custom control loginctrl

 

Public loginctrl ()

{

The declared child controls and events should be initialized here.

// Initialize the properties of the control.

This. lblusername. Text = "User name :";

This. lblpassword. Text = "Password :";

This.txt password. textmode = system. Web. UI. webcontrols. textboxmode. Password;

 

This. pnlframe. width = 240;

This. pnlframe. Height = 120;

This. pnlframe. backcolor = color. empty;

// Add the submit button and click the event

Submitbutton. Text = "OK ";

Submitbutton. Click + = new eventhandler (this. submitbtn_click );

// Add reset button click event

Clearbutton. Text = "reset ";

Clearbutton. Click + = new eventhandler (this. clearbtn_click );

// Add the declared child controls to loginctrl

This. Controls. Add (this. submitbutton );

This. Controls. Add (this. clearbutton );

This.controls.add(this.txt username );

This.controls.add(this.txt password );

This. Controls. Add (this. lblusername );

This. Controls. Add (this. lblpassword );

This. Controls. Add (this. pnlframe );

}

Add or reload the public attributes that match the control as needed

// Font color attribute

[Bindable (false ),

Category ("appearance "),

Defaultvalue ("")]

Public override color forecolor

{

Get

{

Return this. _ fontcolor;

}

Set

{

This. _ fontcolor = value;

}

}

// Control background attributes

[Bindable (false ),

Category ("appearance "),

Defaultvalue ("")]

Public override color backcolor

{

Get

{

Return this. _ backcolor;

}

 

Set

{

This. _ backcolor = value;

}

}

// User name attributes

[Bindable (false ),

Category ("appearance "),

Defaultvalue ("")]

Public String Username

{

Get

{

Return this.txt username. text;

}

Set

{

This.txt username. Text = value;

}

}

// Password attributes

[Bindable (false ),

Category ("appearance "),

Defaultvalue (""), browsable (false)]

Public String Password

{

Get

{

Return this.txt password. text;

}

Set

{

This.txt password. Text = value;

}

}

// Control width attribute

[Bindable (false ),

Category ("appearance "),

Defaultvalue ("")]

Create an ASP. NET web custom control-routine 3
Create an ASP. NET web custom control-routine 3

This seriesArticle"Routine 1" and "routine 2" describes how to use the existing web custom controls in Visual Studio. net2003 to generate custom controls you need by inheriting or combining some simple controls. This control is relatively simple to create, but its execution efficiency is relatively low. So if we do not inherit the existing control, how should we do this control?

The following describes the programming method of this self-writing control through examples.

(Routine uses C #)

This routine implements a Textbox, which tests the input string and replaces the single quotation marks with single quotation marks (single quotation marks lead to database errors ).

The control must first inherit the base class of all controls: system. web. UI. control: implements two interfaces: istatemanager (viewstate) and ipostbackdatahandler (processing the returned data. web. UI. webcontrols. textbox to write some common attributes and methods. Due to space limitations, this example only implements the text attribute.

Using system;

Using system. Web. UI;

Using system. Web. UI. webcontrols;

Using system. componentmodel;

 

Namespace demo

{

/// <Summary>

/// Summary of webcustomcontrol1.

/// </Summary>

Like in the previous two examples, you can first process the properties of the control during design.

[Defaultproperty ("text "),

Designer ("demo. demodesigner "),

Toolboxdata ("<{0}: demotextbox runat = Server> </{0}: demotextbox>")]

Public class demotextbox: system. Web. UI. Control, istatemanager, ipostbackdatahandler

{

Private statebag _ state;

Private bool _ marked;

 

The following are the attributes we want to implement: Text

[Bindable (true ),

Category ("appearance "),

Defaultvalue ("")]

Public String text

{

Get

{

String _ text = (string) viewstate ["text"];

Return _ text = NULL? "": _ Text;

}

 

Set

{

String text = "";

TEXT = value;

TEXT = text. Replace ("'","'");

Viewstate ["text"] = text;

}

}

Istatemanager interface must be implemented to achieve view status.

Object istatemanager. saveviewstate ()

{

Object _ stateState = NULL;

If (_ state! = NULL)

_ StateState = (istatemanager) _ state). saveviewstate ();

 

If (_ stateState = NULL)

Return NULL;

 

Return _ stateState;

}

 

Void istatemanager. trackviewstate ()

{

_ Marked = true;

 

If (_ state! = NULL)

(Istatemanager) _ state). trackviewstate ();

}

 

Void istatemanager. loadviewstate (object state)

{

If (State! = NULL)

{

Object _ newstate = (object) State;

(Istatemanager) viewstate). loadviewstate (_ newstate );

}

}

 

Bool istatemanager. istrackingviewstate

{

Get

{

Return _ marked;

}

}

 

Internal new statebag viewstate // note that the viewstate attribute of the base class is overwritten here.

{

Get

{

If (_ state = NULL)

{

_ State = new statebag (true );

If (istatemanager) This). istrackingviewstate)

(Istatemanager) _ state). trackviewstate ();

}

Return _ state;

}

}

 

The following shows the output of the control to the page. In fact, system. Web. UI. webcontrols. textbox repacks the input.

Protected override void render (htmltextwriter output)

{

String stroutput = "<input name = \" "+ this. clientid + "\" type = \ "text \" value = \ "" + this. text + "\"> ";

Output. Write (stroutput );

}

# Region ipostbackdatahandler Member

 

Public void raisepostdatachangedevent ()

{

// Todo: Add demotextbox. raisepostdatachangedevent implementation

}

The following method is very important to save the returned data.

Public bool loadpostdata (string postdatakey, system. Collections. Specialized. namevaluecollection postcollection)

{

// Todo: Add demotextbox. loadpostdata implementation

String presentvalue = This. text;

String postedvalue = postcollection [postdatakey];

If (! Presentvalue. Equals (postedvalue) // If the returned data is not equal to the original data

{

This. Text = postedvalue;

Return true;

}

Return false;

}

 

# Endregion

}

}

 

Now, a self-written Textbox Control is complete. If you think it is difficult to implement viewstate, you can set the inherited base class to system. web. UI. change control to system. web. UI. webcontrols. webcontrol. In this way, you only need to implement ipostbackdatahandler, And the viewstate control can solve the problem by yourself.

 

Related Article

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.