这几天学习了一些数据绑定的知识。写一个随笔记录下来。方便以后用时查找,同时也把学的总结一下。

1、<%# %>

用<%# %>可以将很多东西绑定到前端。如变量、属性、数据源、服务器端的方法。

1.1 绑定属性和变量

当使用<%#%>绑定属性和变量时,有两个很重要的地方:(1)属性或变量一定要是public。(2)、在页面一定要记得加上Page.DataBind()

View Code
 1 protected void Page_Load(object sender, EventArgs e)
 2     {
 3         Page.DataBind();
 4     }
 5     public string name = "张三";
 6     public string Name
 7     {
 8         get
 9         {
10             return "李四";
11         }
12     }
13 
14 
15  <div>
16                 <p><%#name %></p>
17                 <p><%#Name %></p>
18 </div>

1.2动态绑定服务器端的控件属性值

页面放两个服务器控件一个是下拉框、一个文本框

1 <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true">
2                     <asp:ListItem Selected="True" Text="1" Value="1"></asp:ListItem>
3                     <asp:ListItem Text="2" Value="2"></asp:ListItem>
4                     <asp:ListItem Text="3" Value="3"></asp:ListItem>
5                 </asp:DropDownList>
6                 <asp:TextBox runat="server" Text="<%#DropDownList1.SelectedValue %>" ID="txtbox1"></asp:TextBox>

当下拉框的值发生改变时,文本框值也会相应的发生变化

1.3绑定服务器端的方法

在后台代码写了一个计算方法,绑定到控件的属性上

复制代码
1 public int sum(int m, int n)
2     {
3         return m + n;
4     }
5 
6 
7 <asp:TextBox runat="server" Text="<%#sum(3,4) %>" ID="TextBox1"></asp:TextBox>
复制代码

1.4Hashtable绑定到DataList
写了一个Hashtable作为数据源绑定数据控件上

复制代码
 1 protected void Page_Load(object sender, EventArgs e)
 2     {
 3         Hashtable ht = new Hashtable();
 4         ht.Add("张三","22");
 5         ht.Add("李四", "23");
 6         ht.Add("王五", "25");
 7         DataList1.DataSource = ht;
 8         DataList1.DataBind();
 9       }
10 
11 
12  <asp:DataList ID="DataList1" runat="server">
13                 <HeaderTemplate>
14                     <table>
15                         <tr>
16                             <td>姓名</td>
17                             <td>年龄</td>
18                         </tr>
19                     </table>
20                 </HeaderTemplate>
21                 <ItemTemplate>
22                     <table>
23                         <tr>
24                             <td>
25                                 <%#((DictionaryEntry)Container.DataItem).Key %>
26                             </td>
27                             <td>
28                                  <%#((DictionaryEntry)Container.DataItem).Value %>
29                             </td>
30                         </tr>
31                     </table>
32                 </ItemTemplate>
33             </asp:DataList>
复制代码

2<%=%>

<%=%>相当于一个  Response.Write(),里面放的是变量然后输出。如果使用<%=%>绑定变量不需要加上Page.DataBind()这一句

1 public string name2 = "王五";
2 
3 
4      <p><%=name2 %></p>

3、<%=%>与<%# %>的区别

1、<%=%>不需要Page.DataBind()

2、<%=%>不能数据源、服务器端方法。而<%# %>可以。