1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 using System; using System.Web.UI; using System.Web.UI.WebControls; using System.ComponentModel; using System.Text; namespace Controls { /// <summary> /// MyTextBox2 的摘要说明。 /// </summary> [ToolboxData("<{0}:MyTextBox2 runat=server></{0}:MyTextBox2>")] public class MyTextBox2 : System.Web.UI.WebControls.WebControl,INamingContainer { private Label lbl; private TextBox txt; protected override void CreateChildControls() { base.CreateChildControls (); lbl = new Label(); lbl.ID = "lbl"; lbl.Style.Add("display", "none"); Controls.Add(lbl); txt = new TextBox(); txt.ID = "txt"; txt.AutoPostBack = true; txt.TextChanged += new EventHandler(txt_TextChanged); Controls.Add(txt); lbl.Attributes.Add("onclick", "showbox(this,‘" + txt.ClientID + "‘);"); ChildControlsCreated = true; } protected override void OnPreRender(EventArgs e) { base.OnPreRender (e); if(txt.Text.Trim().Length == 0) return; double t = 0; try { t = double.Parse(txt.Text.Trim()); } catch(Exception ex) { ex.ToString(); } lbl.Text = t.ToString("c"); } protected override void RenderChildren(HtmlTextWriter writer) { StringBuilder sb = new StringBuilder(); sb.Append("<script language=‘javascript‘>"); sb.Append("function showbox(lbl,txtID){lbl.style.display=‘none‘;var txt=document.getElementById(txtID);txt.style.display=‘block‘;}"); sb.Append("</script>"); this.Page.RegisterStartupScript("MyTextBox2JS", sb.ToString()); lbl.RenderControl(writer); txt.RenderControl(writer); } protected override HtmlTextWriterTag TagKey { get { return HtmlTextWriterTag.Div; } } private void txt_TextChanged(object sender, EventArgs e) { if(txt.Text.Trim().Length == 0) return; double t = 0; try { t = double.Parse(txt.Text.Trim()); } catch(Exception ex) { ex.ToString(); } lbl.Style.Add("display", "block"); lbl.Text = t.ToString("c"); txt.Style.Add("display", "none"); } } }