C # aspx page Data binding method collection

Source: Internet
Author: User
Tags bind eval reflection static class trim xpath

C # ASP Tutorial x page Data binding method collection

1. Eval ("") and Bind ("") these two one-way bindings, a two-way binding, bind is a two-way binding, but need data source support
asp.net tutorial 2.0 improves data-binding operations in the template, simplifying the data-binding syntax DataBinder.Eval (Container.DataItem, fieldname) in v1.x to Eval (fieldname). The Eval method, like DataBinder.Eval, can accept an optional format string parameter. The difference between the shortened eval syntax and the DataBinder.Eval is that Eval automatically parses the fields based on the DataItem properties of the nearest container object (such as DataListItem), and DataBinder.Eval needs to use parameters to specify the container. For this reason, eval can only be used in a data-bound control's template, not the page layer. Of course, DataBinder.Eval is still supported on the ASP.net 2.0 page, and you can use it in an environment that does not support simplified eval syntax.
The following example shows how to use the new simplified eval data binding syntax to bind to the image, label, and Hyperlink controls in the DataList data item template (ItemTemplate).


<asp:datalist id= "DataList1" repeatcolumns= "5" width= "" runat= "Server" datasourceid= "ObjectDataSource1" >
<itemtemplate>
<asp:hyperlink id= "HyperLink1" runat= "Server" navigateurl= "<%#" eval ("PhotoID", "photoformviewplain.aspx?id={0 } ")%> ' > <asp:image id=" image1 "runat=" Server "imageurl= <%# eval (" filename "," images/thumbs/{0} ")%>/&G T;</asp:hyperlink>
<asp:label id= "CaptionLabel" runat= "server" text= ' <%# eval ("caption")%> '/>
</itemtemplate>
</asp:datalist>
<asp:objectdatasource id= "ObjectDataSource1" runat= "Server" Typename= " Datacomponenttableadapters.photostableadapter "selectmethod=" Getphotosforalbum ">


2. Data binding can also be part of a control's subject definition (theme definition) so that we can change the layout and appearance of the templated control arbitrarily by changing the theme. However, the theme (subject) template can only use eval (or the bind discussed later). Binding to arbitrary user code is prohibited.

DataBinder.Eval usage


Show two decimal places
<%# DataBinder.Eval (Container.DataItem, "UnitPrice", "${0:f2}")%>
{0:g} represents true or False
<itemtemplate>
<asp:image width= "height=" "border=" 0 "runat=" server "alternatetext= ' <%# DataBinder.Eval ( Container.DataItem, "discontinued", "{0:g}")%> '
Imageurl= ' <%# DataBinder.Eval (Container.DataItem, "discontinued", "~/images/{0:g}.gif")%> '/>
</itemtemplate>
Conversion type
((String) DataBinder.Eval (container, "DATAITEM.P_SHIP_TIME_SBM8")). Substring (4,4)
{0:D} Date only shows year month day
{0:YYYY-MM-DD} Displays the date of year by format
{0:C} currency style


Container.DataItem usage.


often uses this procedure when binding data: <%# DataBinder.Eval
(Container.DataItem, "xxxx")%> or <%# DataBinder.Eval
( Container, "dataitem.xxxx")%>
There is another, and Microsoft says this method is more efficient than the above two.
<%# (DataRowView) container.dataitem) ["xxxx"]%>
is useful, so you can do a lot of things on the front page. The
also remembers that you must import the namespace System.Data in the foreground page, or you will generate an error message.
<%@ Import namespace= "System.Data"%>
this usage actually and <%# ((dictionaryentry) Container.DataItem) .key%> is a truth.
The key is to container this thing, its namespace is System.ComponentModel.


The difference between 3.databinder.eval and Container.DataItem
           What is the difference between  
DataBinder.Eval (Container.DataItem, "name") and Container.DataItem ("name")? The
DataBinder is a static class inside system.web that provides an eval method for simplifying the writing of data-binding expressions, but it is used in ways that are easy to use through expensive methods such as reflection, so their performance is not the best. Container is not any static object or method at all, it is a local variable declared within the data-bound event handler by the asp.net page compiler, and its type is the data container type of the control that can be data-bound (for example, the data binding within the Repeater The container is called RepeaterItem, and there are basically dataitem properties in these container classes, so you can write Container.DataItem, which returns the data item in the data source you are binding to. If your data source is a DataTable, the type of the data item is actually DataRowView. The
Reference: http://www.cnblogs.com/yangjunwl/articles/1120560.html
Data-binding expression must be contained between <% #和%> characters. The format is as follows:
<tagprefix:tagname property= ' <%# data-binding expression%> ' runat= ' server '/>
or as follows:
< % # data-binding expression%>


asp.net supports hierarchical data-binding models that use the eval and bind methods to bind data to controls and submit changes back to the database tutorial.
The Eval method is a static one-way (read-only) method, so the Eval function is used for one-way (read-only) binding, which takes the value of a data field as a parameter and returns it as a string.
The Bind method supports read/write functionality, so the BIND function is used for bidirectional (updatable) bindings. This method retrieves the value of a data-bound control and submits any changes back to the database.
The XPath method supports providing support for data sources of XML types.


Where do the data-binding expressions appear on the page?
One, you can include a data-binding expression in the value side of a property name/attribute value pair in the start tag of a server control or plain HTML element. For example:
<asp:textbox id= "TextBox1" runat= "Server" text= ' <% #数据绑定表达式%> ' ></asp:textbox><br/>


Note: At this point the binding expression of the data can be a variable, or it can be a C # or VB.net method with a return value, or it can be the value of a property of a control, or it can be the value of a C # or a field or property of a VB.net object, and so on. Of course, it can be directly a string, such as "Hello".
If the data-binding expression at this point is eval (a field in a table in the database), and so on, you must place the textbox1 in the template of a loop-displayed control, or you will be prompted for Eval (), XPath (), and bind () This type of data-binding method can only be used in the context of a data-bound control. In fact, you want to put TextBox1 in the template of a control like Repeater,datalist,gridview.


Second, the data-bound expression is contained anywhere in the page. For example:
<form id= "Form1" runat= "Server" >
<div>
<% #eval ("data-binding Expression 1")%>
<% #eval ("data-binding Expression 2")%>
</div>
</form>


Also follow the "one" notice clause.
If the data-binding expression at this point is eval (a field in a table in the database) and so on, you must put the <% #eval (data Binding expression 1)%> <% #eval ("Data Binding Expression 2")%> like Repeater, Datalist,gridview in a template for such a control.


Third, you can include data-binding expressions in the Web page special effects code to implement methods that call C # or vb.net in JavaScript. For example:
deafult2.aspx:@ page language= "C #" autoeventwireup= "true" codefile= "Default2.aspx.cs" inherits= "DEFAULT2"%>
<!doctype HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/ Xhtml1-transitional.dtd ">
<title> Untitled Page </title>
<script language = "javascript" type= "Text/javascript" >
function Getstr ()
{
var A;
A = ';
A= ' <% #csharptojavascript ()%> '//Call method for C #
alert (a);
}
</script>
<body>
<form id= "Form1" runat= "Server" >
<div>
<input id= "button1" type= "button" value= "JavaScript calls the C # Method!" onclick= "Getstr ()"/</div>
</form>
</body>
Default2.cs:system;
Using System.Data;
Using System.Configuration;
Using System.Collections;
Using System.Web;
Using System.Web.Security;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.web.ui.webcontrols.webparts;
Using System.Web.UI.HtmlControls;
public partial class Default2:system.web.ui.page
{
protected void Page_Load (object sender, EventArgs e)
{
The Page.DataBind ()//method has the return value to bind first in order to implement the method that JavaScript calls C #!
}
public string Csharptojavascript ()
{
Return "JavaScript calls the C # Method!";
}
}


What types of data-binding expressions can be?
1, can be a variable
For example: <asp:label id= "Label1" runat= "Server" text= "<% #变量名%>" ></asp:label>
2, can be the property value of the server control
For example: <asp:label id= "Label1" runat= "Server" text= "<% #textbox2. Text%>" ></asp:label>
3, can be an array and other collection objects
For example, to bind an array to a list control, such as a ListBox, or a control such as Repeater,datalist,gridview, you only need to datasource= the property to the ' <%# array name%> '.
4, can be an expression
For example: The person is an object, name and city are its 2 properties, then the data-binding expression can be written like this:
<%# (Person.name + "" + person.city)%>.
5, can be a method
For example: <% #getusername ()%>. GetUserName () is a defined C # method that generally requires a return value.
6, can be obtained by using Eval,datebind.eval data table fields, this is the most common, no longer examples.
Note: If a data-binding expression is the value of a property, as long as there are no double quotes in the data-binding expression, the outermost layer of the <% #数据绑定表达式%> can be in double quotes or single quotes. If double quotes appear in a data-binding expression, it is best to use single quotes for the outermost layer of the <% #数据绑定表达式%>.


Common methods for data-binding expressions related to databases?
1,<% #databind. Eval (Container.DataItem, field name)%>
<% #databind. Eval (Container.DataItem, "field name", "{0:c}")%>
There are 2 other kinds of less common:
<%# DataBinder.Eval (Container, "DataItem. Field name")%>
<%# DataBinder.Eval (Container, "DataItem. Field name", {0:c})%>
Container.DataItem is equivalent to a row of records in a table in a database, and a row can have many columns.
The last parameter is the same as the String.Format form. For example, c for currency, p for percent semicolon, D for short date format display, F for floating-point reality, F3 for three decimal points, one analogy.
Use the three-mesh operator: Example:
<%# DataBinder.Eval (Container.DataItem, field name). ToString (). Trim (). length>16? DataBinder.Eval (Container.DataItem, field name). ToString (). Trim (). substring (0,16):d Atabinder.eval (Container.DataItem , "field name"). ToString (). Trim ()%>
2,<% #eval (field name)%>
<% #eval ("Field name", "{0:c}")%>
. NET 2.0 a new method that appears. and Databind.eval () equivalence.
The last parameter is the same as the String.Format form. For example, c for currency, p for percent semicolon, D for short date format display, F for floating-point reality, F3 for three digits after the decimal point, one analogy.
Examples of using the three-mesh operator:
<%# (eval ("gender")). ToString () = = "true"? Male ":" Female "%>
Gender field type is: Yes/No (access), bit (SQL Server)
Examples of using method calls:
<%# Getuserphoto (eval ("Photopath"))%>
Definition of Getuserphoto ():
String Getuserphoto (Object Photopath) {
if (Photopath = = DBNull.Value) <%# ((DataRowView) container.dataitem) [Field name]%>
{
Return "}
Else
{
Return "}
}
3, <%# ((DataRowView) container.dataitem) [Field name]%>
<%# String.Format ("{0:c}", ((DataRowView) container.dataitem) [Field name])%> sets the display style of the field with the String.Format method. For example, c for currency, p for percent semicolon, D for short date format display, F for floating-point reality, F3 for three decimal points, one analogy.
Type Conversion Example: <%# (int) (DataRowView) container.dataitem) [Field name 1]* (int) ((DataRowView) container.dataitem) [Field Name 2]% > meaning is 2 characters San multiply.
Efficiency of the above three binding methods: The DataBinder.Eval method is invoked when the Eval method executes, and the DataBinder.Eval method performs late-bound computations using reflection at run time, resulting in a noticeable decrease in performance. So it can cause a noticeable drop in performance. So the <%# ((DataRowView) Container.DataItem) ["Field name"]%> the best of the three.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.