Data-bound server controls

Source: Internet
Author: User
Tags bind bool count eval expression integer numeric value tostring
Server | control | Data data Binding server control

Data Binding Overview and syntax
ASP.net introduces a new declarative data-binding syntax. This very flexible syntax allows developers not only to bind to a data source, but also to bind to a simple property, a collection, an expression, or even a result returned from a method call. The following table shows some examples of the new syntax.


Simple Properties Customer: <%# CustID%>
Collection Orders: <asp:listbox id= "List1" datasource= ' <%# myarray '%> ' "Server" >
Expression Contact: <%# (Customer. The Name + "" + customer. LastName)%>
Method results Outstanding Balance: <%# getbalance (CustID)%>

Although the syntax looks similar to the ASP's Response.Write shortcut <%=%>, its behavior is completely different. ASP Response.Write Shortcut syntax is evaluated while the page is being processed, and asp.net data-binding syntax is evaluated only when the DataBind method is invoked.

DataBind is the method for pages and all server controls. When DataBind is invoked on a parent control, it is cascaded to all child controls of the control. For example, Datalist1.databind () will therefore invoke the DataBind method for each control in the DataList template. Calling Databind-page.databind () or just DataBind () on a page causes all data-binding expressions on the calculated page to be evaluated. DataBind is usually called from the Page_Load event, as shown in the following example.


protected void Page_Load (Object Src, EventArgs E) {
DataBind ();
}


Protected Sub Page_Load (Src as Object, E as EventArgs)
DataBind ()
End Sub


protected function Page_Load (Src:object, E:eventargs): void {
DataBind ();
}

If the binding expression evaluates to the expected data type at run time, you can use the binding expression in almost any location in the declaration section of the. aspx page. The simple properties, expressions, and method examples above display text to the user when evaluated. In these cases, the data-binding expression must evaluate to a String-type value. In the collection example, the data-binding expression evaluates to a valid type value for the DataSource property of the ListBox. You may find it necessary to convert the value of the type in the binding expression to produce the desired result. For example, if Count is an integer:


Number of Records: <%# count. ToString ()%>


Binding to Simple properties
asp.net data-binding syntax supports properties that are bound to public variables, page properties, and other controls on the page.

The following example shows how to bind to a common variable and a simple property on a page. Note that these values are initialized before the DataBind () call.



<script language= "C #" runat= "Server" >

void Page_Load (Object sender, EventArgs e) {
Page.DataBind ();
}

String custid{
get {
return "ALFKI";
}
}

int ordercount{
get {
return 11;
}
}


</script>

<body>


<form runat=server>

Customer: <b><%# CustID%></b><br>
Open order: <b><%# ordercount%></b>

</form>

</body>

The following example shows how to bind to a property of another control.


<script language= "C #" runat= "Server" >

void SubmitBtn_Click (Object sender, EventArgs e) {

Call only "Page.DataBind", not from "StateList"
To explicitly remove the variable, and then manipulate the label control.
This calculates all the <%#%> expressions in the page

Page.DataBind ();
}

</script>

<body>


<form runat=server>

<asp:dropdownlist id= "statelist" runat= "Server" >
<asp:ListItem>CA</asp:ListItem>
<asp:ListItem>IN</asp:ListItem>
<asp:ListItem>KS</asp:ListItem>
<asp:ListItem>MD</asp:ListItem>
<asp:ListItem>MI</asp:ListItem>
<asp:ListItem>OR</asp:ListItem>
<asp:ListItem>TN</asp:ListItem>
<asp:ListItem>UT</asp:ListItem>
</asp:DropDownList>

<asp:button text= "Submit" onclick= "SubmitBtn_Click" runat=server/>

<p>

Selected states: <asp:label text= ' <%# StateList.SelectedItem.Text%> ' runat=server/>

</form>

</body>


Binding to collections and lists

List server controls such as the DataGrid, ListBox, and HtmlSelect use the collection as a data source. The following example shows how to bind to the usual common language runtime collection type. These controls can only be bound to a collection that supports IEnumerable, ICollection, or IListSource interfaces. The most common is binding to ArrayList, Hashtable, DataView, and DataReader.


The following example shows how to bind to a ArrayList.



<script language= "C #" runat= "Server" >

void Page_Load (Object Sender, EventArgs E) {

if (! Page.IsPostBack) {

ArrayList values = new ArrayList ();

Values. ADD ("in");
Values. ADD ("KS");
Values. ADD ("MD");
Values. ADD ("MI");
Values. ADD ("OR");
Values. ADD ("TN");

Dropdown1.datasource = values;
Dropdown1.databind ();
}
}

void SubmitBtn_Click (Object sender, EventArgs e) {
Label1.Text = "you selected:" + DropDown1.SelectedItem.Text;
}

</script>

<body>


<form runat=server>

<asp:dropdownlist id= "DropDown1" runat= "Server"/>

<asp:button text= "Submit" onclick= "SubmitBtn_Click" runat=server/>

<p>

<asp:label id=label1 font-name= "song Body" font-size= "10.5pt" runat= "Server"/>

</form>

</body>

The following example shows how to bind to a DataView. Note the DataView class is defined in the System.Data namespace.

<%@ Import namespace= "System.Data"%>



<script language= "C #" runat= "Server" >

void Page_Load (Object sender, EventArgs e) {

if (! Page.IsPostBack) {

DataTable dt = new DataTable ();
DataRow Dr;

Dt. Columns.Add (New DataColumn ("Integer value", typeof (Int32));
Dt. Columns.Add (New DataColumn ("String Value", typeof (String));
Dt. Columns.Add (New DataColumn ("Date Time value", typeof (DateTime));
Dt. Columns.Add (New DataColumn ("Boolean", typeof (BOOL));

for (int i = 1; I <= 9; i++) {

Dr = dt. NewRow ();

Dr[0] = i;
DR[1] = "Item" + i.tostring ();
DR[2] = DateTime.Now;
DR[3] = (i% 2!= 0)? True:false;

Dt. Rows.Add (DR);
}

DataGrid1.DataSource = new DataView (DT);
Datagrid1.databind ();
}
}

</script>

<body>


<form runat=server>

<asp:datagrid id= "DATAGRID1" runat= "Server"
Bordercolor= "BLACK"
Borderwidth= "1"
Gridlines= "Both"
Cellpadding= "3"
cellspacing= "0"
Headerstyle-backcolor= "#aaaadd"
/>

</form>

</body>


The following example shows how to bind to a Hashtable.


<script language= "C #" runat= "Server" >

void Page_Load (Object sender, EventArgs e) {
if (! Page.IsPostBack) {

Hashtable h = new Hashtable ();
H.add ("Key 1", "value 1");
H.add ("Key 2", "Value 2");
H.add ("Key 3", "Value 3");

Mydatalist.datasource = h;
Mydatalist.databind ();
}
}

</script>

<body>


<form runat=server>

<asp:datalist id= "mydatalist" runat= "Server"
Bordercolor= "BLACK"
Borderwidth= "1"
Gridlines= "Both"
Cellpadding= "4"
cellspacing= "0"
>

<ItemTemplate>
<%# ((DictionaryEntry) Container.DataItem). Key%>:
<%# ((DictionaryEntry) Container.DataItem). Value%>
</ItemTemplate>

</asp:DataList>

</form>

</body>


Binding an expression or method

You typically need to manipulate data before you bind to a page or control. The following example shows how to bind to the return value of an expression and a method.


<script language= "C #" runat= "Server" >

void Page_Load (Object Src, EventArgs E) {

if (! Page.IsPostBack) {

ArrayList values = new ArrayList ();

Values. ADD (0);
Values. ADD (1);
Values. ADD (2);
Values. ADD (3);
Values. ADD (4);
Values. ADD (5);
Values. ADD (6);

Datalist1.datasource = values;
Datalist1.databind ();
}
}

String evenorodd (int number) {
if ((number% 2) = = 0)
return "even";
Else
return "odd";
}

</script>

<body>


<form runat=server>

<asp:datalist id= "DataList1" runat= "Server"
Bordercolor= "BLACK"
Borderwidth= "1"
Gridlines= "Both"
Cellpadding= "3"
cellspacing= "0"
>

<ItemTemplate>
Numeric value: <%# Container.DataItem%>
Odd/Odd: <%# evenorodd ((int) container.dataitem)%>
</ItemTemplate>

</asp:datalist>

</form>

</body>
DataBinder.Eval

The ASP.net framework provides a static method for calculating late-bound data-binding expressions and optionally formatting the result as a string. DataBinder.Eval is convenient because it eliminates many of the explicit conversions that developers must do to force the value to be converted to the desired data type. This is especially useful in controls that are in the list of data-bound templates, because the types of data rows and data fields typically must be converted.

Take a look at the example below, in this case the integer will appear as a currency string. Using the standard asp.net data binding syntax, you must first convert the type of the data row to retrieve the data field IntegerValue. Next, pass this as a parameter to the String.Format method.


<%# String.Format ("{0:c}", ((DataRowView) container.dataitem) ["IntegerValue"])%>


<%# String.Format ("{0:c}", (CType (Container.DataItem, DataRowView) ("IntegerValue"))%>


<%# String.Format ("{0:c}", (DataRowView (Container.DataItem)) ["IntegerValue"])%>


C # VB JScript



This syntax may be more complex and difficult to remember. Instead, DataBinder.Eval is just a method with three parameters: the name container for the data item, the data field name, and the format string. In a list of templates such as DataList, DataGrid, or Repeater, the naming container is always container.dataitem. The Page is another naming container that you can use with DataBinder.Eval.



<%# DataBinder.Eval (Container.DataItem, "IntegerValue", "{0:c}")%>


<%# DataBinder.Eval (Container.DataItem, "IntegerValue", "{0:c}")%>


<%# DataBinder.Eval (Container.DataItem, "IntegerValue", "{0:c}")%>


C # VB JScript



The format string parameter is optional. If omitted, DataBinder.Eval returns the value of the object type, as shown in the following example.



<%# (BOOL) DataBinder.Eval (Container.DataItem, "Boolvalue")%>


<%# CType (DataBinder.Eval (Container.DataItem, "Boolvalue"), Boolean)%>


<%# Boolean (DataBinder.Eval (Container.DataItem, "Boolvalue"))%>


C # VB JScript



DataBinder.Eval has a significant performance penalty for standard data-binding syntax because it uses late-bound reflection, which is important to note. You need to be cautious when using databinder.eval, especially if you don't need string formatting.

<%@ Import namespace= "System.Data"%>



<script language= "C #" runat= "Server" >

void Page_Load (Object sender, EventArgs e) {

if (! Page.IsPostBack) {

DataTable dt = new DataTable ();
DataRow Dr;

Dt. Columns.Add (New DataColumn ("IntegerValue", typeof (Int32));
Dt. Columns.Add (New DataColumn ("StringValue", typeof (String));
Dt. Columns.Add (New DataColumn ("Datetimevalue", typeof (DateTime));
Dt. Columns.Add (New DataColumn ("Boolvalue", typeof (BOOL));

for (int i = 0; i < 9; i++) {

Dr = dt. NewRow ();

Dr[0] = i;
DR[1] = "Item" + i.tostring ();
DR[2] = DateTime.Now;
DR[3] = (i% 2!= 0)? True:false;

Dt. Rows.Add (DR);
}

Datalist1.datasource = new DataView (DT);
Datalist1.databind ();
}
}

</script>

<body>


<form runat=server>

<asp:datalist id= "DataList1" runat= "Server"
Repeatcolumns= "3"
Width= "80%"
Bordercolor= "BLACK"
Borderwidth= "1"
Gridlines= "Both"
Cellpadding= "4"
cellspacing= "0"
>

<ItemTemplate>

Order Date: <%# DataBinder.Eval (Container.DataItem, "Datetimevalue", "{0:d}")%>

<p>

Quantity: <%# DataBinder.Eval (Container.DataItem, "IntegerValue", "{0:n2}")%>

<p>

Item: <%# DataBinder.Eval (Container.DataItem, "StringValue")%>

Order Date: <asp:checkbox id=chk1 checked= ' <%# (bool) DataBinder.Eval (Container.DataItem, "Boolvalue")%> ' runat= Server/>

<p>

</ItemTemplate>

</asp:Datalist>

</form>

</body>


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.