控制項是圖形用戶界面的小型構建塊,其中包括文本框、按鈕、複選框、列表框、標籤和許多其他工具。使用這些工具,用戶可以輸入數據、進行選擇並指示他們的首選項。
控制項還用於結構作業,如驗證、數據訪問、安全性、創建母版頁和數據操作。
ASP.NET使用五種類型的web控制項,它們是:
- HTML controls
- HTML Server controls
- ASP.NET Server controls
- ASP.NET Ajax Server controls
- User controls and custom controls
ASP.NET伺服器控制項是ASP.NET中使用的主要控制項。這些控制項可以分爲以下類別:
驗證控制項—這些控制項用於驗證用戶輸入,它們通過運行客戶端腳本來工作。
數據源控制項-這些控制項提供到不同數據源的數據綁定。
數據視圖控制項-它們是各種列表和表,可以綁定到數據源中的數據以供顯示。
個性化設置控制項-這些控制項用於根據用戶首選項根據用戶信息對頁面進行個性化設置。
登錄和安全控制-這些控制提供用戶身份驗證。
母版頁-這些控制項在整個應用程式中提供一致的布局和界面。
導航控制項-這些控制項有助於導航。例如,菜單、樹視圖等。
豐富的控制項-這些控制項實現特殊功能。例如,AdRotator、FileUpload和Calendar控制項。
使用伺服器控制項的語法爲:
<asp:controlType ID ="ControlID" runat="server" Property1=value1 [Property2=value2] />
此外,visual studio還具有以下功能,可幫助生成無錯誤編碼:
- Dragging and dropping of controls in design view
- IntelliSense feature that displays and auto-completes the properties
- The properties window to set the property values directly
Properties of the Server Controls
具有可視方面的ASP.NET伺服器控制項派生自WebControl類,並繼承該類的所有屬性、事件和方法。
Web Control類本身和其他一些未可視化呈現的伺服器控制項是從System.Web.UI.Control類派生的。例如,占位符控制項或XML控制項。
ASP.Net伺服器控制項繼承WebControl和System.Web.UI.Control類的所有屬性、事件和方法。
下表顯示了所有伺服器控制項通用的繼承屬性:
Property | Description |
---|---|
AccessKey | Pressing this key with the Alt key moves focus to the control. |
Attributes | It is the collection of arbitrary attributes (for rendering only) that do not correspond to properties on the control. |
BackColor | Background color. |
BindingContainer | The control that contains this control's data binding. |
BorderColor | Border color. |
BorderStyle | Border style. |
BorderWidth | Border width. |
CausesValidation | Indicates if it causes validation. |
ChildControlCreated | It indicates whether the server control's child controls have been created. |
ClientID | Control ID for HTML markup. |
Context | The HttpContext object associated with the server control. |
Controls | Collection of all controls contained within the control. |
ControlStyle | The style of the Web server control. |
CssClass | CSS class |
DataItemContainer | Gets a reference to the naming container if the naming container implements IDataItemContainer. |
DataKeysContainer | Gets a reference to the naming container if the naming container implements IDataKeysControl. |
DesignMode | It indicates whether the control is being used on a design surface. |
DisabledCssClass | Gets or sets the CSS class to apply to the rendered HTML element when the control is disabled. |
Enabled | Indicates whether the control is grayed out. |
EnableTheming | Indicates whether theming applies to the control. |
EnableViewState | Indicates whether the view state of the control is maintained. |
Events | Gets a list of event handler delegates for the control. |
Font | Font. |
Forecolor | Foreground color. |
HasAttributes | Indicates whether the control has attributes set. |
HasChildViewState | Indicates whether the current server control's child controls have any saved view-state settings. |
Height | Height in pixels or %. |
ID | Identifier for the control. |
IsChildControlStateCleared | Indicates whether controls contained within this control have control state. |
IsEnabled | Gets a value indicating whether the control is enabled. |
IsTrackingViewState | It indicates whether the server control is saving changes to its view state. |
IsViewStateEnabled | It indicates whether view state is enabled for this control. |
LoadViewStateById | It indicates whether the control participates in loading its view state by ID instead of index. |
Page | Page containing the control. |
Parent | Parent control. |
RenderingCompatibility | It specifies the ASP.NET version that the rendered HTML will be compatible with. |
Site | The container that hosts the current control when rendered on a design surface. |
SkinID | Gets or sets the skin to apply to the control. |
Style | Gets a collection of text attributes that will be rendered as a style attribute on the outer tag of the Web server control. |
TabIndex | Gets or sets the tab index of the Web server control. |
TagKey | Gets the HtmlTextWriterTag value that corresponds to this Web server control. |
TagName | Gets the name of the control tag. |
TemplateControl | The template that contains this control. |
TemplateSourceDirectory | Gets the virtual directory of the page or control containing this control. |
ToolTip | Gets or sets the text displayed when the mouse pointer hovers over the web server control. |
UniqueID | Unique identifier. |
ViewState | Gets a dictionary of state information that saves and restores the view state of a server control across multiple requests for the same page. |
ViewStateIgnoreCase | It indicates whether the StateBag object is case-insensitive. |
ViewStateMode | Gets or sets the view-state mode of this control. |
Visible | It indicates whether a server control is visible. |
Width | Gets or sets the width of the Web server control. |
Methods of the Server Controls
下表提供了伺服器控制項的方法:
Method | Description |
---|---|
AddAttributesToRender | Adds HTML attributes and styles that need to be rendered to the specified HtmlTextWriterTag. |
AddedControl | Called after a child control is added to the Controls collection of the control object. |
AddParsedSubObject | Notifies the server control that an element, either XML or HTML, was parsed, and adds the element to the server control's control collection. |
ApplyStyleSheetSkin | Applies the style properties defined in the page style sheet to the control. |
ClearCachedClientID | Infrastructure. Sets the cached ClientID value to null. |
ClearChildControlState | Deletes the control-state information for the server control's child controls. |
ClearChildState | Deletes the view-state and control-state information for all the server control's child controls. |
ClearChildViewState | Deletes the view-state information for all the server control's child controls. |
CreateChildControls | Used in creating child controls. |
CreateControlCollection | Creates a new ControlCollection object to hold the child controls. |
CreateControlStyle | Creates the style object that is used to implement all style related properties. |
DataBind | Binds a data source to the server control and all its child controls. |
DataBind(Boolean) | Binds a data source to the server control and all its child controls with an option to raise the DataBinding event. |
DataBindChildren | Binds a data source to the server control's child controls. |
Dispose | Enables a server control to perform final clean up before it is released from memory. |
EnsureChildControls | Determines whether the server control contains child controls. If it does not, it creates child controls. |
EnsureID | Creates an identifier for controls that do not have an identifier. |
Equals(Object) | Determines whether the specified object is equal to the current object. |
Finalize | Allows an object to attempt to free resources and perform other cleanup operations before the object is reclaimed by garbage collection. |
FindControl(String) | Searches the current naming container for a server control with the specified id parameter. |
FindControl(String, Int32) | Searches the current naming container for a server control with the specified id and an integer. |
Focus | Sets input focus to a control. |
GetDesignModeState | Gets design-time data for a control. |
GetType | Gets the type of the current instance. |
GetUniqueIDRelativeTo | Returns the prefixed portion of the UniqueID property of the specified control. |
HasControls | Determines if the server control contains any child controls. |
HasEvents | Indicates whether events are registered for the control or any child controls. |
IsLiteralContent | Determines if the server control holds only literal content. |
LoadControlState | Restores control-state information. |
LoadViewState | Restores view-state information. |
MapPathSecure | Retrieves the physical path that a virtual path, either absolute or relative, maps to. |
MemberwiseClone | Creates a shallow copy of the current object. |
MergeStyle | Copies any nonblank elements of the specified style to the web control, but does not overwrite any existing style elements of the control. |
OnBubbleEvent | Determines whether the event for the server control is passed up the page's UI server control hierarchy. |
OnDataBinding | Raises the data binding event. |
OnInit | Raises the Init event. |
OnLoad | Raises the Load event. |
OnPreRender | Raises the PreRender event. |
OnUnload | Raises the Unload event. |
OpenFile | Gets a Stream used to read a file. |
RemovedControl | Called after a child control is removed from the controls collection of the control object. |
Render | Renders the control to the specified HTML writer. |
RenderBeginTag | Renders the HTML opening tag of the control to the specified writer. |
RenderChildren | Outputs the contents of a server control's children to a provided HtmlTextWriter object, which writes the contents to be rendered on the client. |
RenderContents | Renders the contents of the control to the specified writer. |
RenderControl(HtmlTextWriter) | Outputs server control content to a provided HtmlTextWriter object and stores tracing information about the control if tracing is enabled. |
RenderEndTag | Renders the HTML closing tag of the control into the specified writer. |
ResolveAdapter | Gets the control adapter responsible for rendering the specified control. |
SaveControlState | Saves any server control state changes that have occurred since the time the page was posted back to the server. |
SaveViewState | Saves any state that was modified after the TrackViewState method was invoked. |
SetDesignModeState | Sets design-time data for a control. |
ToString | Returns a string that represents the current object. |
TrackViewState | Causes the control to track changes to its view state so that they can be stored in the object's view state property. |
Example
讓我們看看一個特定的伺服器控制項-樹狀視圖控制項。樹視圖控制項位於導航控制項下。其他導航控制項有:菜單控制項和站點映射路徑控制項。
在頁面上添加樹視圖控制項。選擇編輯節點。。。從任務中。使用樹狀圖節點編輯器編輯每個節點,如圖所示:
創建節點後,在「設計」視圖中如下所示:
自動套用格式。。。任務允許您設置樹狀圖的格式,如下所示:
在頁面上添加一個label控制項和一個文本框控制項,並分別將它們命名爲lblmessage和txtmessage。
編寫幾行代碼,以確保選中特定節點時,label控制項顯示節點文本,文本框顯示其下的所有子節點(如果有)。文件後面的代碼應該如下所示:
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; namespace eventdemo { public partial class treeviewdemo : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { txtmessage.Text = " "; } protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e) { txtmessage.Text = " "; lblmessage.Text = "Selected node changed to: " + TreeView1.SelectedNode.Text; TreeNodeCollection childnodes = TreeView1.SelectedNode.ChildNodes; if(childnodes != null) { txtmessage.Text = " "; foreach (TreeNode t in childnodes) { txtmessage.Text += t.Value; } } } } }
執行頁面以查看效果。您將能夠展開和摺疊節點。