If you're new here, you may want to subscribe to our RSS feed as well as to our NewsLetter (on Top Right hand menu) to get highly informative articles weekly...and NO, we never spam! Если вы новичок на сайте, Вы можете подписаться на наш канал, а также наши с новостями (по началу Правое меню), чтобы получить весьма информативным статей неделю ... и НЕТ, мы никогда не спам!
The job of each server-side control is to render a particular area of the asp page. Задача каждой серверной стороны контроля для оказания конкретной области asp страницы. The page contains a list of such controls which were added by the coder and when the time to show the page to the user come every control in that list is called to render itself. Страница содержит список такого контроля, которые были добавлены в кодере и когда время показать страницу пользователя при каждом контроля в этом списке называется оказывать сама. The supported function of predefining the way controls render themselves give the coder to express a particular data in unlimited ways. Поддерживает функцию predefining способ контроля делают сами дать кодировщику выразить особое данных в неограниченных путей.
How Custom DataBound Controls works Как обычай DataBound контроля работает
Every server-side control in ASP.NET derives from System.Web.UI.Control even the Page class. Каждый серверной стороны контроля в ASP.NET вытекает из System.Web.UI.Control даже Page класса. The Control class has a “Render” virtual function with a single parameter of type HtmlTextWriter which is responsible for how the control will be presented to user. Контроль класса "Визуализация" виртуальные функции с одним параметром типа HtmlTextWriter который отвечает за контроль того, как будет представлено пользователю.
Practice Rendering Custom ontrols Практика оказания таможенных ontrols
The best way to introduce the benefits of rendering custom controls is the practice method. Лучший способ представления преимуществ делает пользовательский контроль практике метод. Let’s assume we have the following table in SQL Допустим, мы имеем следующие таблицы в SQL 
The page we are going to create should show every user from the database who has article_result more than ‘0’. Странице мы собираемся создавать должны показать каждому пользователю из базы данных, который article_result более'0 '. So follow the next steps: Поэтому следить за следующие шаги:
1. Create a simple Web site containing one default.aspx page. Создать простой веб-сайт, содержащий одну страницу default.aspx.
2. Build the data table above or use another data source. Build таблице данных выше или использовать другой источник данных.
3. Create a new Web Control library. Создать новый Web контролю библиотеки. 
4. Declare in the control appropriate dataset. Объявление в контроле соответствующих данных.
5. Override the RenderContents function. Перекрыть RenderContents функции.
protected override void RenderContents ( HtmlTextWriter output ) { if ( !DesignMode ) { String s = "" ; s += ( @ " <table >" ) ; s += ( @ " <tr>" ) ; foreach ( DataColumn c in UserDataSet. Columns ) { s += ( @ " <td border=" "2" " style=" "width: 130px; background-color:Silver" ">" ) ; s += c. ColumnName ; s += ( @ " <td/>" ) ; } s += ( @ " <tr/>" ) ; foreach ( DataRow dr in UserDataSet. Rows ) { s += ( @ " <tr>" ) ; foreach ( DataColumn c in dr. Table . Columns ) { s += ( @ " <td border=" "1" " style=" "width: 130px; background-color:WhiteSmoke" ">" ) ; if ( dr. Table . Columns . IndexOf ( c ) == 2 ) { for ( int i = 0 ; i < ( int ) dr [ c ] ; i++ ) { s += ( "X" ) ; } } else { s += dr [ c ] . ToString ( ) ; } s += ( @ " <td/>" ) ; } s += ( @ " <tr/>" ) ; } output. Write ( s ) ; } else { output. Write ( "Design mode, no data loaded!" ) ; } } охраняемых переопределить недействительным RenderContents (HtmlTextWriter производства) (если (! DesignMode) (Строка ы = ""; ы + = (@ "имя_табличного_пространства>"); ы + = (@ "<tr>"); foreach (DataColumn с в UserDataSet. Столбцы) (ы + = (@ "<td border=" "2"" style=" "width: 130px; background-color:Silver" "> "); Ы + = c. ColumnName; Ы + = ( @ "<td/>");) ы + = (@ "<tr/>"); foreach (DataRow -dr в UserDataSet. строк) (ы + = (@ "<tr>"); foreach (DataColumn с в -dr. Таблица. Столбцы) (ы + = (@ "<td border=" "1"" style=" "width: 130px; background-color:WhiteSmoke" "> "); если (dr. таблице. Колонки. IndexOf (с) == 2) (для (я int = 0; я <(int) -dr [с]; я + +) (ы + = ( "X");)) еще (ы + = -dr [с] . ToString ();) ы + = (@ "<td/>");) ы + = (@ "<tr/>");) производства. Написать (ы);) (другой продукции. Написать ( "Дизайн режиме, никаких данных загружается! ");)) 6. Put the control in the default page and fill the dataset with data. Разместите контроля в стандартной страницы и заполнения данных с данными.
<% @ Page Language= "C#" AutoEventWireup= "true" CodeFile= "Default.aspx.cs" Inherits= "_Default" %> <% @ Register Assembly= "MyWebCustomControl" Namespace= "MyWebCustomControl" TagPrefix= "cc1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" > <html xmlns= "http://www.w3.org/1999/xhtml" > <head runat= "server" > <title>Untitled Page</title> </head> <body> <form id= "form1" runat= "server" > <div style= "text-align: center" > <cc1:webcustomcontrol1 id= "WebCustomControl1_1" runat= "server" height= "35px" width= "420px" ></cc1:webcustomcontrol1> </div> </form> </body> </html> protected void Page_Load ( object sender, EventArgs e ) { UserDataSetTableAdapters. GetUsersWithArticleResultTableAdapter da = new UserDataSetTableAdapters. GetUsersWithArticleResultTableAdapter ( ) ; WebCustomControl1_1. UserDataSet = ( DataTable ) da. GetData ( ) ; } <% @ Page Язык = "C #" AutoEventWireup = "истинного" CodeFile = "Default.aspx.cs" Инхериц = "_Default"%> <% @ Зарегистрируйтесь Ассамблеи = "MyWebCustomControl" имен = "MyWebCustomControl" TagPrefix = "cc1 "%> <! DOCTYPE <a ОБЩЕСТВЕННОГО "- / / W3C / / DTD XHTML 1.0 Transitional / / EN" "Fanuc"> < <a задавать = "http://www.w3.org/1999/xhtml"> <head runat= "server"> <title> Untitled Page </ название> </ Руководитель> <body> <форма ИД = "form1" runat = "сервера"> <div style= "text-align: center"> <cc1:webcustomcontrol1 id= "WebCustomControl1_1" runat= "server" height= width= "35px" "420px"> </ cc1: webcustomcontrol1 > </ div> </ форму> </ тела> </ <a> охраняемых недействительным Page_Load (объект отправителя, EventArgs е) (UserDataSetTableAdapters. GetUsersWithArticleResultTableAdapter да = UserDataSetTableAdapters новые. GetUsersWithArticleResultTableAdapter (); WebCustomControl1_1. UserDataSet = (DataTable ) да. GetData ();) And here is the result. И вот - результат.

This reminds to a simple databound table except the third column, but in fact changing the code in RenderContents function makes data presentation very flexible. Это напоминает на простой databound таблице, за исключением третьей колонке, но на самом деле изменения кода RenderContents функции представления данных позволяет очень гибко. Server controls gives the coder complete control over the generated html. Сервер контроля позволяет кодировщику полный контроль над созданный <a. The given sample custom rendered control is not finished enough to be served to the end user. Данная пользовательский контроля вынесено не завершена, чтобы отбыть на конечного пользователя. Custom rendered controls usually manage a set of properties, fire events to their hosts, and render snapshots of themselves to their hosts. Пользовательские вынес контроля управления, как правило, набор свойств, огня событий принимающих их, и делают снимки сами по себе их хосты.
The code above is not the best example for independence of browser version. Этот код не является лучшим примером для независимости версии браузера. In ASP.NET 2.0 is added an adaptive rendering model, which inserts only those html tags and elements supported by the browser. В ASP.NET 2.0 добавлено адаптивное делает модель, которая вставляет только те HTML- теги и элементы поддерживает браузер.
Links you may find interesting - Ссылки вы можете найти интересные -
- How to Build Perfect and Best Navigation System in ASP for your Website Как Build Perfect и оптимальной системы навигации в ASP для вашего сайта
- How to Combine Java and ASP.NET ? Как комбинировать Java и ASP.NET?
- How to use GDI+ with ASP.NET controls Как использовать GDI + с ASP.NET контроля
- Rolling a Content Management System from Scratch with PHP, MySQL, TinyButStrong and FCKEditor Подвижной Система управления контентом от записи с PHP, MySQL, TinyButStrong и FCKEditor
- How to Build Themed WebSite in ASP.Net Как построить тематический сайт в asp.net














