原理和那個适應寬度的TextBox查不多,隻是這個反而更加簡單,因為在高度方向上增長不會破壞頁面的整體布局效果(寬度上的如果在頁内會擠走别的元素的),是以就不需要使用Agent
TextBox來作為實際錄入的容器了,直接把<TextArea>增高就行了。
響應onpropertychange事件,同步内容和<TextArea>的高度。當然如果完全根據内容增高可能也會因為内容太多而變得難看,就設定了一個最大高度限制屬性。控件效果如下:
最大高度為200px的AutoTextBox Demo:
最大高度為200px但初始高度為3rows的AutoTextBox Demo:
高度增長無限制的AutoTextBox Demo:
如果控件的MaxHeight屬性小于或等于0,那麼增長高度無限制。
#region 附 AutoTextBox 控件源碼
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
namespace WebExcel.UI.WebControls
{
/// <summary>
/// Summary description for AutoLengthTextBox.
/// </summary>
[DefaultProperty("Text"),
ToolboxData("<{0}:AutoTextArea runat=server></{0}:AutoTextArea>")]
public class AutoTextArea : System.Web.UI.WebControls.TextBox
{
[DefaultValue(200)]
public int MaxHeight
{
get
{
object obj = ViewState["MaxHeight"];
return obj == null ? 200 : (int)obj;
}
set
ViewState["MaxHeight"] = value;
}
[DefaultValue(60)]
public int MinHeight
object obj = ViewState["MinHeight"];
return obj == null ? 60 : (int)obj;
ViewState["MinHeight"] = value;
protected override void OnPreRender(EventArgs e)
this.Attributes["minHeight"] = this.MinHeight.ToString();
if ( this.Height == Unit.Empty )
this.Height = this.MinHeight;
else
this.Height = (int)Math.Max(this.MinHeight, this.Height.Value);
base.OnPreRender (e);
/// <summary>
/// Render this control to the output parameter specified.
/// </summary>
/// <param name="output"> The HTML writer to write out to </param>
protected override void Render(HtmlTextWriter output)
string strCode;
if ( this.MaxHeight <= 0 )
strCode = "this.style.height=Math.max(this.minHeight,this.scrollHeight)+(this.offsetHeight-this.clientHeight)";
strCode = "this.style.height=(this.scrollHeight>200)?200:Math.max(this.minHeight,this.scrollHeight)+(this.offsetHeight-this.clientHeight)";
base.Attributes["onpropertychange"] = strCode;
// base.Attributes["onfocus"] = "this.height=this.height";
if ( base.Rows == 0 )
base.Rows = 1;
base.TextMode = TextBoxMode.MultiLine;
base.Render(output);
}
}
#endregion
本文轉自部落格園鳥食軒的部落格,原文連結:http://www.cnblogs.com/birdshome/,如需轉載請自行聯系原部落客。