Summary
In the previous article, we wrote a very simple webpart that could only output a string of Hello world!.
It is clear that this WebPart has no practical effect at all. Is there a way to write something more complicated, like a WebPart with events?
This article describes how to write a WebPart with events.
Body
To implement a WebPart with events, it is actually implementing a WebPart with a composite control, which is of great practical significance in the development process. If we can do this, then, what other WebPart, I believe that we can do extrapolate.
Here, I use a textbox, a button control to give an example, to do is to click the button, the current system time can be displayed in the TextBox.
As for the basic operation of WebPart, it is clear from the previous article that there are no more than one by one steps to explain the operation.
To facilitate your study, you can download the project created by this article.
The procedures for each step are recorded below.
1, first create a namespace for Eallies.WebParts.Sample C # class Library project, and the default Class1.cs renamed to Time.cs. Then add the system.web reference and change the AssemblyInfo.cs as described in the previous article.
Change the Time.cs code to the following code:
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4 5 using System.Web.UI;
6 using System.Web.UI.WebControls;
7 using System.Web.UI.WebControls.WebParts;
8 using System.Web.UI.HtmlControls; 9 namespace Eallies.WebParts.Sample One {public class Time:webpart, INamingContainer {priv
Ate string _text;
Private HtmlTableCell _htmltablecell = new HtmlTableCell ();
The private textbox _textbox = new TextBox ();
Private button _button = New button (); This._button.click + + = Delegate (object sender, EventArgs e) 24 {this._text = DateTime.Now.ToString (); this._htmltablecell.innerhtml =
""; this.
Addcontrols ();
29}; [WebBrowsable (True), personalizable (true)]--public string Text 34 {35 get {return _text;} 36 set {_text = value;} protected override void CreateChildControls () 40 {41 This.
Controls.Add (New LiteralControl ("<table>" + "\ n")); This is.
Controls.Add (New LiteralControl ("<tr>" + "\ n")); this.
Controls.Add (This._htmltablecell); This is.
Controls.Add (New LiteralControl ("</tr>" + "\ n")); this.
Controls.Add (New LiteralControl ("</table>" + "\ n")); The IF (this. Page.IsPostBack = = False) this.
Addcontrols (); m protected override void OnLoad (EventArgs e).
OnLoad (e); The IF (this. Page.IsPostBack = = True) this.
Addcontrols (); The protected override void Render (HtmlTextWriter writer) is the base.
Render (writer); The private void Addcontrols () is this._textbox.id = this.id + "Tex"Tbox ";
This._textbox.text = This._text;
This._htmltablecell.controls.add (This._textbox);
This._htmltablecell.controls.add (New LiteralControl ("<br>"));
This._button.id = this.id + "button";
This._button.text = "Get Time";
This._htmltablecell.controls.add (This._button); 73} 74} 75}