数据绑定的总结

DataBind 是页和所有服务器控件的方法。当在父控件上调用 DataBind 时,它级联到该控件的所有子控件。例如,DataList1.DataBind() 将因此对 DataList 模板中的每一控件调用 DataBind 方法。在页上调用 DataBind — Page.DataBind() 或只是 DataBind() — 会导致计算页上的所有数据绑定表达式。通常从 Page_Load 事件调用 DataBind,如下例所示。

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(Srcbject, E:EventArgs) : void {
    DataBind();
}

C#        VB        JScript         

如果绑定表达式在运行时计算为预期的数据类型,则可以在 .aspx 页的声明节中的几乎任何位置使用绑定表达式。上面的简单属性、表达式和方法示例在计算时向用户显示文本。这些情况下,数据绑定表达式必须计算为 String 类型的值。在集合示例中,数据绑定表达式计算为 ListBox 的 DataSource 属性的有效类型值。您可能会发现有必要转换绑定表达式中的类型值以产生所需的结果。例如,如果 count 是整数:

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

绑定到简单属性

ASP.NET 数据绑定语法支持绑定到公共变量、页的属性和页上其他控件的属性。

下面的示例说明如何绑定到公共变量和页上的简单属性。注意这些值在 DataBind() 调用前初始化。
1<html>
2<head>
3    <script language="C#" runat="server">
4
5        void Page_Load(Object sender, EventArgs e) {
6            Page.DataBind();
7        }
8       
9        string custID{
10            get {
11                return "ALFKI";
12            }
13        }
14       
15        int orderCount{
16            get {
17                return 11;
18            }
19        }
20
21
22    </script>
23
24</head>
25<body>
26
27    <h3><font face="Verdana">DataBinding to a Property on the Page</font></h3>
28
29    <form runat=server>
30   
31        Customer: <b><%# custID %></b><br>
32        Open Orders: <b><%# orderCount %></b>
33
34    </form>
35
36</body>
37</html>
38
39



下面的示例说明如何绑定到另一控件的属性
<html>
<head>
    <script language="C#" runat="server">

        void SubmitBtn_Click(Object sender, EventArgs e) {
       
          // Rather than explictly pull out the variable from the "StateList"
          // and then manipulate a label control, just call "Page.DataBind".
          // This will evaluate any <%# %> expressions within the page
         
          Page.DataBind();
        }

    </script>

</head>
<body>

    <h3><font face="Verdana">DataBinding to a property of another server control</font></h3>

    <form runat=server>

        <aspropDownList id="StateList" runat="server">
          <aspistItem>CA</aspistItem>
          <aspistItem>IN</aspistItem>
          <aspistItem>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>
        </aspropDownList>
       
        <asp:button Text="Submit"  runat=server/>
       
        <p>
       
        Selected State: <asp:label text='<%# StateList.SelectedItem.Text %>' runat=server/>
       
    </form>

</body>
</html>


绑定到集合和列表

像 DataGrid、ListBox 和 HTMLSelect 这样的列表服务器控件将集合用作数据源。下面的示例说明如何绑定到通常的公共语言运行库集合类型。这些控件只能绑定到支持 IEnumerable、ICollection 或 IListSource 接口的集合。最常见的是绑定到 ArrayList、Hashtable、DataView 和 DataReader。
下面的示例说明如何绑定到 ArrayList。
<html>
<head>

    <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 chose: " + DropDown1.SelectedItem.Text;
        }

    </script>

</head>
<body>

    <h3><font face="Verdana">DataBinding DropDownList</font></h3>

    <form runat=server>
   
        <aspropDownList id="DropDown1" runat="server" />

        <asp:button Text="Submit"  runat=server/>

        <p>
       
        <asp:Label id=Label1 font-name="Verdana" font-size="10pt" runat="server" />

    </form>

</body>
</html>



下面的示例说明如何绑定到 DataView。注意 DataView 类在 System.Data 命名空间

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

<html>
<head>

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

        void Page_Load(Object sender, EventArgs e ) {
       
                        if (!Page.IsPostBack)
                  {
           
                  DataTable dt = new DataTable();
                    //dt为声明一个表
               
                DataRow dr;
                //表示Table中行的数据

                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("BooleanValue", typeof(bool)));
                //Columns为取值该表列的集合,
                //Add.为该表添加到列的集合 DataColumn为列框架
                //后面是列头的标题,后面表示该列的数据类型

               

                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中
                dataGrid1.DataBind();
            }
        }

    </script>

</head>
<body>

    <h3><font face="Verdana">Databinding to a DataView</font></h3>

    <form runat=server>

        <aspataGrid id="dataGrid1" runat="server"
          BorderColor="black"
          BorderWidth="1"
          GridLines="Both"
          CellPadding="3"
          CellSpacing="0"
          HeaderStyle-BackColor="#aaaadd"
        />

    </form>

</body>
</html>

下面的示例说明如何绑定到 Hashtable
<html>
<head>

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

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

                Hashtable h = new Hashtable();
                h.Add ("key1", "value1");
                h.Add ("key2", "value2");
                h.Add ("key3", "value3");
             

                MyDataList.DataSource = h;
                MyDataList.DataBind();
            }
        }

    </script>

</head>
<body>

    <h3><font face="Verdana">DataBinding to a Hashtable</font></h3>

    <form runat=server ID="Form1">

        <aspataList 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>
</html>

绑定表达式或方法

通常需要在绑定到页或控件之前操作数据。下面的示例说明如何绑定到表达式和方法的返回值。
<html>
<head>

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

        void Page_Load(Object Src, EventArgs E) {

            if (!Page.IsPostBack) {

              ArrayList values = new ArrayList();
              //新建一个数组实例value
              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();
            //把数组绑定到DataList1 
             
            }
        }

        String EvenOrOdd(int number) {
            if ((number % 2) == 0)
              return "Even";
            else
              return "Odd";
              //这里新建了一方法EvenOrOdd 接收传递进来的参数number
            //  然后进行计算然后返回结果
        }

    </script>

</head>
<body>

    <h3><font face="Verdana">Databinding to Methods and Expressions</font></h3>

    <form runat=server ID="Form1">

      <asp:DataList id="DataList1" runat="server"
        BorderColor="black"
        BorderWidth="1"
        GridLines="Both"
        CellPadding="3"
        CellSpacing="0"
        >

        <ItemTemplate>
          Number Value: <%# Container.DataItem %><br>
          Even/Odd: <%# EvenOrOdd((int) Container.DataItem) %>
          //这里必须小心的注意语句 EvenOrOdd((int) Container.DataItem) 是把(int)Container.DataItem
          //作为一个整体参数传递方法EvenOrOdd 这个是值得我去学习
          //就是把一个数据绑定的数据,通过计算 然后返回一个 数据绑定的结果,
          //这也说明 我们可以对对数据绑定的数据进行操作了
        </ItemTemplate>

      </aspatalist>

    </form>

</body>
</html>

DataBinder.Eval

ASP.NET Framework 提供了一种静态方法,计算后期绑定的数据绑定表达式并且可选择将结果格式化为字符串。DataBinder.Eval 很方便,因为它消除了开发人员为强迫将值转换为所需的数据类型而必须做的许多显式转换。这在数据绑定模板列表内的控件时尤其有用,因为通常数据行和数据字段的类型都必须转换。

请看下面的示例,本例中整数将显示为货币字符串。使用标准的 ASP.NET 数据绑定语法,必须首先转换数据行的类型以便检索数据字段 IntegerValue。下一步,将此作为参数传递给 String.Format 方法。

<%# 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         

该语法可能比较复杂,难以记忆。相反,DataBinder.Eval 是只有三个参数的简单方法:数据项的命名容器、数据字段名和格式字符串。在像 DataList、DataGrid 或 Repeater 这样的模板列表中,命名容器始终是 Container.DataItem。Page 是另一个可与 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         

格式字符串参数是可选的。如果省略它,则 DataBinder.Eval 返回对象类型的值,如下例所示。

<%# (bool)DataBinder.Eval(Container.DataItem, "BoolValue") %>

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

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

C#        VB        JScript         

DataBinder.Eval 会对标准数据绑定语法带来很明显的性能损失,因为它使用后期绑定反射,注意这一点很重要。使用 DataBinder.Eval 时需谨慎,尤其是在不需要字符串格式化时。

         

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

<html>
<head>

    <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>

</head>
<body>

    <h3><font face="Verdana">Databinding Using DataBinder.Eval</font></h3>

    <form runat=server ID="Form1">

        <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}") %>

                <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/>
                //上面这几个要注意DataBinder.Eval的用法和 {O}和{0:N2}代表的意思
                <p>

            </ItemTemplate>

        </asp:Datalist>

    </form>

</body>
</html>


本节小结

  1. ASP.NET 声明性数据绑定语法使用 <%# %> 表示法。
  2. 可以绑定到数据源、页或其他控件的属性、集合、表达式以及从方法调用返回的结果。
  3. 列表控件可以绑定到支持 ICollection、IEnumerable 或 IListSource 接口的集合,如 ArrayList、Hashtable、DataView 和 DataReader。
  4. DataBinder.Eval 是用于晚期绑定的静态方法。它的语法可能比标准数据绑定语法简单,但性能较低。